Home > Web Front-end > JS Tutorial > How Control Flow Bindings work in KnockoutJs

How Control Flow Bindings work in KnockoutJs

DDD
Release: 2024-11-24 09:23:09
Original
991 people have browsed it

Como funcionam Bindings de Fluxo de Controle no 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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login
Copy after login
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template