Custom bind to observable array not calling update

2019-07-04 03:22发布

问题:

I have this very simple binding:

ko.bindingHandlers.chosen = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        console.log("INIT");
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        console.log("IT WORKS!");
    }
};

Used in a select:

<select data-bind="
        options: Options,
        chosen: Options
    "></select>

Options is declared as:

this.Options = ko.observableArray(opt1);

And updated, when necessary, like this:

this.Options(newValues);

However, "IT WORKS" gets logged only one time (when the select list is rendered) and never again. See this jsfiddle. Try to press the "reload" button: the array is updated, the select list re-rendered (yay!) but the custom update function isn't called (nay!). I even tried to force .valueHasMutated but with no success.

I need the update function to work properly. Why isn't this happening?

回答1:

It isn't happening because you don't use valueAccessor in update function. If you used it you would get update function fired:

ko.bindingHandlers.chosen = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        console.log("INIT");
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var value = ko.unwrap(valueAccessor());
        console.log("IT WORKS!");
    }
};

Here is updated fiddle: http://jsfiddle.net/wzTg4/8/