How to use custom binding with ko.observableArray()

后端 未结 1 833
不思量自难忘°
不思量自难忘° 2021-01-12 07:01

How does knockout custom binding work with observableArray? When using ko.observable() with custom binding, everything works as expected. When using ko.observableArray(), on

相关标签:
1条回答
  • 2021-01-12 07:16

    You will want to create a dependency on your observableArray within your custom binding. So, at the very least something like:

        ko.bindingHandlers.updateBinding = {
            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                alert("Binding Handler (Init)");
            },
            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
                //create a dependency, normally you would do something with 'data'
                var data = ko.utils.unwrapObservable(valueAccessor());
                alert("Binding Handler (Update)");
            }
        };
    

    The reason that this works with your observable example is because all bindings on a single element are triggered together (more info here).

    The reason that this does not behave the same way on your other binding is that foreach behaves differently. Changes to the observableArray do not trigger the foreach binding directly (or the whole section would be re-rendered). Instead it triggers logic in a separate ko.computed that evaluates how the array has changed and makes the necessary incremental updates (add an item, remove an item, etc.).

    0 讨论(0)
提交回复
热议问题