This article mainly introduces the creation method of Knockout custom binding. For more information, see
Overview
In addition to the built-in binding types (such as value and text) of KO listed in the previous article, you can also create custom binding.
Register Your binding handler
ko.bindingHandlers.yourBindingName = { init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { // This will be called when the binding is first applied to an element // Set up any initial state, event handlers, etc. here }, update: function(element, valueAccessor, allBindings, viewModel, bindingContext) { // This will be called once when the binding is first applied to an element, // and again whenever any observables/computeds that are accessed change // Update the DOM element based on the supplied values here. }};
Next, you can use custom binding on any dom element:
Note: you do not have to provide both init and update callback in your handler. You can provide any one.
Update callback
As the name suggests, when your monitoring attribute observable is updated, ko will automatically call your update callback.
It has the following parameters:
Element: Use the bound dom element;
ValueAccessor: Call valueAccessor () to obtain the currently bound model attribute value. Call ko. unwrap (valueAccessor () to obtain the observable value and common value more conveniently;
AllBindings: All attribute values of the model bound to the dom element. For example, call callBindings. get ('name') returns the bound name attribute value (undefined is returned if no value exists), or calls allBindings. has ('name') determines whether the name is bound to the current dom;
ViewModel: The viewModel is deprecated in Knockout.3x. You can use bindingContext. $ data or bindingContext. $ rawData to obtain the current viewModel;
BindingContext: bindingContext. You can call bindingContext. $ data, bindingContext. $ parent, bindingContext. $ parents to obtain data;
Next, let's take an example. You may want to use the visible binding to control the visibility of elements and add the animation effect. In this case, you can create your custom binding:
ko.bindingHandlers.slideVisible = { update: function(element, valueAccessor, allBindings) { // First get the latest data that we're bound to var value = valueAccessor(); // Next, whether or not the supplied model property is observable, get its current value var valueUnwrapped = ko.unwrap(value); // Grab some more data from another binding property var duration = allBindings.get('slideDuration') || 400; // 400ms is default duration unless otherwise specified // Now manipulate the DOM element if (valueUnwrapped == true) $(element).slideDown(duration); // Make the element visible else $(element).slideUp(duration); // Make the element invisible }};
Then you can use the custom binding as follows:
You have selected the option
Gift wrap