Reputation: 34188
i like to know what is difference between Init and update function of knockout js custom binding ?
when we should write code inside init function and when we should go for update function of knockout js custom binding.
i go through knockout js doc but still my understanding for knockout js custom binding is not very clear to me.
i just wonder if someone help me to understand when we go for init and when we go for update with example.
here i am point out some code which not very clear and their intention.
<div data-bind="allowBindings: true">
<!-- This will display Replacement, because bindings are applied -->
<div data-bind="text: 'Replacement'">Original</div>
</div>
<div data-bind="allowBindings: false">
<!-- This will display Original, because bindings are not applied -->
<div data-bind="text: 'Replacement'">Original</div>
</div>
ko.bindingHandlers.allowBindings = {
init: function(elem, valueAccessor) {
// Let bindings proceed as normal *only if* my value is false
var shouldAllowBindings = ko.unwrap(valueAccessor());
return { controlsDescendantBindings: !shouldAllowBindings };
}
};
<input type="text" data-bind="value: someText, customBinding: someText">
ko.bindingHandlers.customBinding = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor());
console.log( JSON.stringify(value) );
}
}
ko.applyBindings({
someText: ko.observable("inital value")
});
Upvotes: 4
Views: 4753
Reputation: 24901
Knockout documentation clearly states where these these methods are used:
Knockout will call your init function once for each DOM element that you use the binding on. There are two main uses for init:
- To set any initial state for the DOM element
- To register any event handlers so that, for example, when the user clicks on or modifies the DOM element, you can change the state of the associated observable
Knockout will call the update callback initially when the binding is applied to an element and track any dependencies (observables/computeds) that you access. When any of these dependencies change, the update callback will be called once again.
Short answer is init
function is called once when the binding is initialized, and update
function is called every time when there is an update in the value bound. You can find examples in the link above, I don't think it is worth copying them here.
Upvotes: 1