js: hooks: allow deferred continuation (match d0ab562b)

The callback now gets an object argument with defer/cont functions.

Like the lua code, the behavior is that each hook event allows at
most one continue, but nothing enforces the order of continuations
if more hook events arrive before prior ones were continued - which
is possible now with the defer option, but wasn't possible before
(continuation was synchronous from the hook event handler).
This commit is contained in:
Avi Halachmi (:avih) 2020-08-07 13:42:27 +03:00
parent 53ee1ae417
commit d5a02dd934
2 changed files with 10 additions and 3 deletions

View File

@ -193,7 +193,7 @@ success, ``fn`` is called always a-sync, ``error`` is empty string on success.
``mp.utils.getpid()`` (LE)
``mp.add_hook(type, priority, fn)``
``mp.add_hook(type, priority, fn(hook))``
``mp.options.read_options(obj [, identifier [, on_update]])`` (types:
string/boolean/number)

View File

@ -126,10 +126,17 @@ function dispatch_message(ev) {
var hooks = []; // array of callbacks, id is index+1
function run_hook(ev) {
var state = 0; // 0:initial, 1:deferred, 2:continued
function do_cont() { return state = 2, mp._hook_continue(ev.hook_id) }
function err() { return mp.msg.error("hook already continued"), undefined }
function usr_defer() { return state == 2 ? err() : (state = 1, true) }
function usr_cont() { return state == 2 ? err() : do_cont() }
var cb = ev.id > 0 && hooks[ev.id - 1];
if (cb)
cb();
mp._hook_continue(ev.hook_id);
cb({ defer: usr_defer, cont: usr_cont });
return state == 0 ? do_cont() : true;
}
mp.add_hook = function add_hook(name, pri, fn) {