How Form Event Bindings work in KnockoutJs
This content is basically a translation of the original materials. The intention is to learn about KnockoutJs for Magento 2 and create content in Portuguese about KnockouJs.
Documentation
- The data-bind syntax
- Binding context
- The "click" binding
- The "event" binding
- The "submit" binding
- The "enable" and "disable" bindings
- The "value" binding
- The "textInput" binding
- The "hasFocus" binding
- The "checked" binding
- The "options" binding
- The "selectedOptions" binding
- The "uniqueName" binding
Bindings
In KnockoutJs, bindings are the way to connect the logic of the ViewModel (the data and business logic) with the View (HTML). In short, it is through bindings that the user interface automatically reflects changes in your data, without the need to directly manipulate the DOM.
Bindings in KnockoutJs work through the data-bind attribute on HTML elements. This attribute is where you specify the binding you want to use and the associated values.
Form Events
Click
The binding click adds an event handler so that the chosen JavaScript function is invoked when the associated DOM element is clicked. This is most commonly used on elements tagged
Each time the element is clicked, this will invoke the method that was passed in the ViewModel, which in turn changes the state of the ViewModel, which causes the UI to be updated.
<div> You've clicked <span data-bind="text: numberOfClicks"></span> times <button data-bind="click: incrementClickCounter">Click me</button> </div> <script type="text/javascript"> ko.applyBindings({ numberOfClicks : ko.observable(0), incrementClickCounter : function() { var previousCount = this.numberOfClicks(); this.numberOfClicks(previousCount + 1); } }); </script>
By default, KnockoutJs will prevent the click event from performing any standard actions. This means that when using binding click on an tag, the browser will just call the function and not navigate to the href of the link. Click-to-click binding is typically used when you are using the link as part of a UI that manipulates the ViewModel, not as a normal hyperlink to another web page. If it is necessary for the standard click action to continue, simply return true in the function.
Event
The binding event allows you to add an event handler for a specified event so that your chosen JavaScript function is invoked when that event is fired for the associated DOM element. This can be used to bind to any event such as key press, mouse hover or mouse exit.
<div> You've clicked <span data-bind="text: numberOfClicks"></span> times <button data-bind="click: incrementClickCounter">Click me</button> </div> <script type="text/javascript"> ko.applyBindings({ numberOfClicks : ko.observable(0), incrementClickCounter : function() { var previousCount = this.numberOfClicks(); this.numberOfClicks(previousCount + 1); } }); </script>
Submit
The binding submit *is a submit binding directive on a form will prevent the browser's default submit action for that form, in other words the browser will call the handler function, but it will not send the form to the server. The *submit binding is typically used when the form is being used as an interface to the ViewModel, not as a normal HTML form. If the form needs to be submitted as a normal HTML form, simply return true from your submission handler.
<div> <div data-bind="event: { mouseover: enableDetails, mouseout: disableDetails }"> Mouse over me </div> <div data-bind="visible: detailsEnabled"> Details </div> </div> <script type="text/javascript"> ko.applyBindings({ detailsEnabled: ko.observable(false), enableDetails: function() { this.detailsEnabled(true); }, disableDetails: function() { this.detailsEnabled(false); } }); </script>
Enable/Disable
binding enable causes the associated DOM element to be enabled when its parameter value is true. binding disable works in the opposite way, causing the associated DOM element to be disabled when its value is true.
<form data-bind="submit: doSomething"> <button type="submit">Submit</button> </form> <script type="text/javascript"> ko.applyBindings({ this.doSomething = function(formElement) { // ... now do something } }); </script>
Value
The binding value *binds the value of the DOM element associated with a property in the *ViewModel. This is typically useful with form elements like ,
When the user edits the value in the associated form control, the value will be updated in the ViewModel. Similarly, when the ViewModel updates the value, this will update the value of the form control on the screen.
<p> <input type='checkbox' data-bind="checked: hasCellphone" /> I have a cellphone </p> <p> Your cellphone number: <input type='text' data-bind="value: cellphoneNumber, enable: hasCellphone" /> </p> <script type="text/javascript"> ko.applyBindings({ hasCellphone : ko.observable(false), cellphoneNumber: "" }); </script>
The binding value works in conjunction with
TextInput
The binding textInput binds a field ( or
<p>Login name: <input data-bind="value: userName" /></p> <p>Password: <input type="password" data-bind="value: userPassword" /></p> <script type="text/javascript"> ko.applyBindings({ userName: ko.observable(""), // Initially blank userPassword: ko.observable("abc"), // Prepopulate }); </script>
The binding textInput, by default, only updates its model when the user moves focus away from the text box. binding textInput updates its model immediately with every keystroke or other text input mechanism.
HasFocus
The binding hasFocus binds the focus state of a DOM element to a ViewModel property. It is a bidirectional connection that when the ViewModel property is set to true or false, the associated element will be focused or unfocused.
<div> You've clicked <span data-bind="text: numberOfClicks"></span> times <button data-bind="click: incrementClickCounter">Click me</button> </div> <script type="text/javascript"> ko.applyBindings({ numberOfClicks : ko.observable(0), incrementClickCounter : function() { var previousCount = this.numberOfClicks(); this.numberOfClicks(previousCount + 1); } }); </script>
Checked
The checked binding binds a checkable form control, i.e. a checkbox () or a radio button () with a property in ViewModel.
<div> <div data-bind="event: { mouseover: enableDetails, mouseout: disableDetails }"> Mouse over me </div> <div data-bind="visible: detailsEnabled"> Details </div> </div> <script type="text/javascript"> ko.applyBindings({ detailsEnabled: ko.observable(false), enableDetails: function() { this.detailsEnabled(true); }, disableDetails: function() { this.detailsEnabled(false); } }); </script>
Options
The binding options controls which options should appear in a drop-down list (
The assigned value must be an array (or Observable Array). The
<form data-bind="submit: doSomething"> <button type="submit">Submit</button> </form> <script type="text/javascript"> ko.applyBindings({ this.doSomething = function(formElement) { // ... now do something } }); </script>
Selected Options
The binding selectedOptions controls which elements in a multi-select list are currently selected. It is intended to be used in conjunction with a
When the user selects or deselects an item in the multi-select list, this adds or removes the corresponding value to an array in the ViewModel. Similarly, assuming it is an Observable Array in ViewModel, whenever you add or remove items from that array, the corresponding items in the UI will be selected or deselected . It is a two-way connection.
<p> <input type='checkbox' data-bind="checked: hasCellphone" /> I have a cellphone </p> <p> Your cellphone number: <input type='text' data-bind="value: cellphoneNumber, enable: hasCellphone" /> </p> <script type="text/javascript"> ko.applyBindings({ hasCellphone : ko.observable(false), cellphoneNumber: "" }); </script>
UniqueName
The binding uniqueName ensures that the bound DOM element has a non-empty name attribute. If the DOM element does not have a name attribute, this connection will provide one and set it to some unique string value.
<p>Login name: <input data-bind="value: userName" /></p> <p>Password: <input type="password" data-bind="value: userPassword" /></p> <script type="text/javascript"> ko.applyBindings({ userName: ko.observable(""), // Initially blank userPassword: ko.observable("abc"), // Prepopulate }); </script>
The above is the detailed content of How Form Event Bindings work in KnockoutJs. For more information, please follow other related articles on the PHP Chinese website!

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











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.

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.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.
