js: read_options: support on_update (match 478a321d)

This is a bit different than the lua code: on script-opts change it
simply re-applies the conf-file and script-opts to the options object,
and if this results in any changed value at options then on_update is
called with the changelist as argument.

This allows a value to revert back to the conf-file value if the
matching script-opts key had a different value and then got deleted.
It also guarantees to call back whenever the options object is
modified, which the lua code doesn't do (e.g. if the caller changed
a value and the observer changed it back - it won't detect a change).
This commit is contained in:
Avi Halachmi (:avih) 2019-12-21 12:13:15 +02:00
parent 05fb6f906d
commit 71ddb22b39
2 changed files with 18 additions and 3 deletions

View File

@ -187,7 +187,8 @@ success, ``fn`` is called always a-sync, ``error`` is empty string on success.
``mp.add_hook(type, priority, fn)``
``mp.options.read_options(obj [, identifier])`` (types: string/boolean/number)
``mp.options.read_options(obj [, identifier [, on_update]])`` (types:
string/boolean/number, ``on_update`` does re-read the config file)
Additional utilities
--------------------

View File

@ -511,8 +511,8 @@ g.require = new_require(SCRIPTDIR_META + "/" + main_script[1]);
/**********************************************************************
* mp.options
*********************************************************************/
function read_options(opts, id) {
id = String(typeof id != "undefined" ? id : mp.get_script_name());
function read_options(opts, id, on_update) {
id = String(id ? id : mp.get_script_name());
mp.msg.debug("reading options for " + id);
var conf, fname = "~~/script-opts/" + id + ".conf";
@ -556,6 +556,20 @@ function read_options(opts, id) {
else
mp.msg.error(info, "Error: can't convert '" + val + "' to " + type);
});
if (on_update) {
mp.observe_property("options/script-opts", "native", function(_n, _v) {
var saved = JSON.parse(JSON.stringify(opts)); // clone
var changelist = {}, changed = false;
read_options(opts, id); // re-apply conf-file + script-opts
for (var key in opts) {
if (opts[key] != saved[key]) // type always stays the same
changelist[key] = changed = true;
}
if (changed)
on_update(changelist);
});
}
}
mp.options = { read_options: read_options };