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

How Bindings work in KnockoutJs

DDD
Release: 2024-11-05 11:22:02
Original
886 people have browsed it

Como funcionam Bindings 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

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.

The data-bind attribute is not native to HTML, although it is perfectly acceptable (it is strictly compatible with HTML 5 and does not cause problems with HTML 4. But since the browser does not recognize this attribute by default, you need to enable Knockout to for it to take effect.

Binding syntax

KnockoutJs' declarative binding system provides a concise and powerful way to bind data to the UI. It is usually easy and obvious to bind to simple data properties or to use single binding. For more complex bindings, it helps to better understand the behavior and syntax of the KnockoutJs binding system.

Today's message is: <span data-bind="text: myMessage"></span>

<!-- related bindings: valueUpdate is a parameter for value -->
Your value: <input data-bind="value: someValue, valueUpdate: 'afterkeydown'" />
 
<!-- unrelated bindings -->
Cellphone: <input data-bind="value: cellphoneNumber, enable: hasCellphone" />
Copy after login
Copy after login

A call consists of two items, the name and the value of the call, separated by a colon. An element can include multiple links (related or unrelated), with each link separated by a comma. The data being used in the current bindings can be referenced by an object. This object is called binding context (binding context).

The binding value can be a single value, variable or literal, or almost any valid JavaScript expression.

Links can include any amount of whitespace (spaces, tabs, and newlines), so you can use them to organize your links however you want.

Links can include JavaScript-style comments (//... and /*...*/). For example:

If a binding is specified without a value, KnockoutJs will give the binding the value undefined.

The context hierarchy is automatically created and managed by KnockoutJS. The following lists the different types of binding contexts provided by KO.

Variável de Contexto Descrição
$root Esta propriedade sempre se refere ao ViewModel de nível superior. Isso torna possível acessar métodos de nível superior para manipular ViewModel. Geralmente esse é o objeto passado para ko.applyBindings.
$data Esta propriedade é muito parecida com a palavra-chave this do Javascript. A propriedade $data em um contexto de ligação refere-se ao objeto ViewModel para o contexto atual.
$index Esta propriedade contém o índice de um item atual de um array dentro de um loop foreach. O valor de $index mudará automaticamente conforme e quando a matriz Observable subjacente for atualizada. Obviamente, este contexto está disponível apenas para ligações foreach.
$parent Esta propriedade refere-se ao objeto ViewModel pai. Isso é útil quando se deseja acessar propriedades externas do ViewModel de dentro de um loop aninhado.
$parentContext Esta propriedade é diferente da $parent, pois a $parent refere-se a dados. Considerando que $parentContext refere-se ao contexto de ligação.
$rawdata Este contexto contém o valor bruto do ViewModel na situação atual. Esta propriedade se assemelha a $data, mas a diferença é que, se o ViewModel for agrupado em Observable, então $data será apenas desembrulhado. O ViewModel e $rawdata tornam-se dados observáveis reais.
$component Este contexto é usado para se referir ao ViewModel daquele componente, quando está dentro de um determinado componente.
$componentTemplateNodes É uma representação de uma matriz de nós DOM passados para esse componente específico quando se está dentro de um modelo de componente específico.

The connection name should generally match a registered connection (built-in or custom) or be a parameter for another connection. If the name doesn't match any of them, KnockoutJs will ignore it (without any errors or warnings). So if a connection doesn't work, first check if the name is correct.

The binding value can be a single value, variable or literal or almost any valid JavaScript expression. Here are examples of various connection values:

Today's message is: <span data-bind="text: myMessage"></span>

<!-- related bindings: valueUpdate is a parameter for value -->
Your value: <input data-bind="value: someValue, valueUpdate: 'afterkeydown'" />
 
<!-- unrelated bindings -->
Cellphone: <input data-bind="value: cellphoneNumber, enable: hasCellphone" />
Copy after login
Copy after login

The above is the detailed content of How 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