Knockout custom binding creation method_javascript skills
Overview
In addition to the built-in binding types of KO listed in the previous article (such as value, text, etc.), you can also create custom bindings.
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:
<div data-bind="yourBindingName: someValue"> </div>
Note: You do not have to provide both init and update callbacks in your handler, you can provide either 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 this bound dom element;
valueAccessor: The currently bound model attribute value can be obtained by calling valueAccessor(). Calling ko.unwrap(valueAccessor()) can more conveniently obtain the observable value and ordinary value;
allBindings: All attribute values bound to the model on this dom element, for example, call callBindings.get('name') to return the bound name attribute value (if it does not exist, return undefined), or call allBindings.has(' name') determines whether name is bound to the current dom;
viewModel : Deprecated in Knockout.3x, you can use bindingContext.$data or bindingContext.$rawData to get the current viewModel;
bindingContext: Binding context, you can call bindingContext.$data, bindingContext.$parent, bindingContext.$parents, etc. to obtain data;
Look at an example next. You may want to use visible binding to control the visibility of elements and add animation effects. 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 } };
You can then use this custom binding like this:
<div data-bind="slideVisible: giftWrap, slideDuration:600">You have selected the option</div> <label><input type="checkbox" data-bind="checked: giftWrap" /> Gift wrap</label> <script type="text/javascript"> var viewModel = { giftWrap: ko.observable(true) }; ko.applyBindings(viewModel); </script>
init callback
ko will call your init function for every dom element that uses binding, it has two main purposes:
(1) Set the initialization state for the dom element;
(2) Register some event handlers, for example: when the user clicks or modifies the dom element, you can change the status of the monitoring attribute;
ko will use the exact same set of parameters as the update callback.
Continuing with the previous example, you may want slideVisible to set the visibility state of the element (without any animation effect) when the page is first displayed, and the animation effect is executed when it changes later. You can follow Here’s how to do it:
ko.bindingHandlers.slideVisible = { init: function(element, valueAccessor) { var value = ko.unwrap(valueAccessor()); // Get the current value of the current property we're bound to $(element).toggle(value); // jQuery will hide/show the element depending on whether "value" or true or false }, update: function(element, valueAccessor, allBindings) { // Leave as before } };
giftWrap is initialized and defined as false (ko.observable(false)). The associated DIV will be hidden during initialization, and then the DIV will be displayed only when the user clicks the checkbox.
You now know how to use update callbacks to update DOM elements when the observable value changes. We can now use another method to do it. For example, when the user performs an action, it can also cause your observable value to be updated, for example:
ko.bindingHandlers.hasFocus = { init: function(element, valueAccessor) { $(element).focus(function() { var value = valueAccessor(); value(true); }); $(element).blur(function() { var value = valueAccessor(); value(false); }); }, update: function(element, valueAccessor) { var value = valueAccessor(); if (ko.unwrap(value)) element.focus(); else element.blur(); } };
Now you can read and write your observable values via the element's "focusedness" binding.
<p>Name: <input data-bind="hasFocus: editingName" /></p> <!-- Showing that we can both read and write the focus state --> <div data-bind="visible: editingName">You're editing the name</div> <button data-bind="enable: !editingName(), click:function() { editingName(true) }">Edit name</button> <script type="text/javascript"> var viewModel = { editingName: ko.observable() }; ko.applyBindings(viewModel); </script>
The above content is the method for creating Knockout custom binding shared by the editor. I hope you like it.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
