How Control Flow 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 "foreach" binding
- The "if" and "ifnot" bindings
- The "with" and "using" bindings
- The "let" 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.
Control Flow
foreach
The binding foreach is used to create repetitions in HTML elements, generating copies of the same element for each item in a collection (like an array or an observable array) in your view model. This allows you to easily create lists or pivot tables that display data from your model.
When the contents of the model array are modified (by adding, moving or deleting its entries), binding of foreach uses an efficient algorithm to find out what changed, so you can update the DOM according to the array. This means it can handle arbitrary combinations of simulated changes.
- When something is added to the array, foreach will render new copies of your model and insert them into the existing DOM;
- When something in the array is deleted, foreach will simply remove the corresponding DOM elements;
- When reordering something in the array (keeping the same object instances), foreach will normally just move the corresponding DOM elements to their new position.
<div> <ul data-bind="foreach: items"> <li data-bind="text: $data"></li> </ul> <ul data-bind="foreach: getItems()"> <li> <span data-bind="text: name"></span> - <span data-bind="text: age"></span> </li> </ul> <ul data-bind="foreach: { data: people, as: 'person' }"></ul> </div>
In this case, the variable $data references the current item being processed in the loop. This allows you to access the properties or values of that item within the loop.
The as directive allows you to define a custom name for the variable that represents the current item in the foreach iteration cycle. This can make code more readable and meaningful.
Sometimes it is necessary that an item in the array is not deleted, but rather hidden, without actually losing track of its existence. This is known as non-destructive deletion. If you need to hide destroyed entries, set the includeDestroyed option to false.
<div> <ul data-bind="foreach: items"> <li data-bind="text: $data"></li> </ul> <ul data-bind="foreach: getItems()"> <li> <span data-bind="text: name"></span> - <span data-bind="text: age"></span> </li> </ul> <ul data-bind="foreach: { data: people, as: 'person' }"></ul> </div>
If you need to perform additional custom logic on the generated DOM elements, you can use any of the following callbacks:
- afterRender: is invoked each time the foreach block is duplicated and inserted into the document, both when foreach is initialized for the first time and when new entries are later added to the associated array;
- afterAdd: is like afterRender, except that it is invoked only when new entries are added to the array (and not when foreach first iterates over the initial contents of the array);
- beforeRemove: is invoked when an item from the array is removed, but before the corresponding DOM nodes are removed. If a beforeRemove callback is specified, you will need to remove DOM nodes manually, i.e. KnockoutJs cannot know when it will be allowed to physically remove DOM nodes;
- beforeMove: is invoked when an item from the array has changed position in the array, but before the corresponding DOM nodes have been moved. Note that beforeMove applies to all array elements whose indexes have changed, so if a new item is inserted at the beginning of an array, the callback (if specified) will be triggered for all others elements, as its index position has increased by one. You can use beforeMove to store the original screen coordinates of affected elements so you can animate their movements in the afterMove callback;
- afterMove: is invoked after an item from the array has changed position in the array and after foreach has updated the DOM to match. Note that afterMove applies to all elements of the array whose indexes have changed, so if a new item is inserted at the beginning of an array, the callback (if specified) will be triggered for all other elements since their index position has increased by one.
if and ifnot
The binding of if causes a section of markup to appear in your document (and have its data binding attributes applied), only if a specified expression evaluates to true (or a true value , such as a non-null object or a non-empty string).
ifnot's binding works exactly like the if binding, except that it inverts the result of any expression that is passed to it.
if and ifnot play a similar role to the vivsible and hidden bindings. The difference is that, with visible, the contained markup always remains in the DOM and always has its data-bind applied – visible binding just uses CSS to toggle the visibility of the containing element. The if link, however, physically adds or removes the markup contained in your DOM and only applies links to descendants if the expression is true. If the expression involves some observable value, the expression will be reevaluated whenever its value changes.
<div> <ul data-bind="foreach: items"> <li data-bind="text: $data"></li> </ul> <ul data-bind="foreach: getItems()"> <li> <span data-bind="text: name"></span> - <span data-bind="text: age"></span> </li> </ul> <ul data-bind="foreach: { data: people, as: 'person' }"></ul> </div>
with and using
The bindings with and using create a new binding context, so that descendant elements are bound in the context of a specified object.
binding with will dynamically add or remove descendant elements depending on whether the associated value is falsy.
The option allows you to define an alias for the new context object. Although it is possible to refer to the object using the $data.
context variable
<div data-bind='foreach: { data: myArray, includeDestroyed: false }'> ... </div>
The using binding was introduced in KnockoutJs 3.5 as a replacement for with when rendering of descendant elements is not desired. Because using reevaluates descendant connections rather than rerendering, each descendant connection will include an additional dependency on the using context.
let
The binding let allows you to define custom binding context properties that you can reference in the bindings of all descendant elements.
<div data-bind="if: exibirMensagem"> <p>Esta mensagem será exibida se 'exibirMensagem' for verdadeiro.</p> </div> <div data-bind="ifnot: exibirMensagem"> <p>Esta mensagem será exibida se 'exibirMensagem' for falso.</p> </div>
The above is the detailed content of How Control Flow 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











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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.
