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

How Observables work in KnockoutJs

Susan Sarandon
Release: 2024-10-29 20:45:03
Original
914 people have browsed it

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

  • KnockoutJs: Observables
  • KnockoutJs: Observables Arrays
  • KnockoutJs: Computed Observables
  • KnockoutJs: Writable Computed Observables
  • KnockoutJs: Pure Computed Observables
  • KnockoutJs: Computed Observables

Observables

KnockoutJs introduces the concept of observables, which are properties that can be monitored and automatically updated when their values ​​change. This functionality allows the user interface to dynamically react to changes in Model.

data

To create an observable in KnockoutJs, you can use the ko.observable() function and assign an initial value to it. To access the current value of an observable, you can treat it as a function. To just observe something without an initial value, just call the Observable property without parameters.

let myObservable = ko.observable('Inicial');

console.log(myObservable()); // Irá imprimir 'Inicial'

myObservable('Novo valor');
console.log(myObservable()); // Irá imprimir 'Novo valor'
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  • ko.isObservable: returns true for observables, observables arrays and all computed observables;
  • ko.isWritableObservable: returns true for observables, observable arrays and writable computed observables.

Subscriptions

The subscriptions in observables are mechanisms that allow you to be notified whenever the value of an observable changes. They are essential for tracking changes in observables and reacting to these changes, updating the user interface or taking other actions when necessary.

The subscribe() method ***receives a *callback function that will be executed whenever the value of the observable is modified. The callback function receives as an argument the new value of the observable. This function accepts three parameters: callback is the function that is called whenever the notification happens, target (optional) defines the value of this in the function callback and event (optional; default is change) is the name of the event to receive notification.

let myObservable = ko.observable('Inicial');

console.log(myObservable()); // Irá imprimir 'Inicial'

myObservable('Novo valor');
console.log(myObservable()); // Irá imprimir 'Novo valor'
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  1. change: This is the default event that triggers the subscription whenever the value of the observable changes. It is the most common event and is used when no other event is explicitly specified;
  2. beforeChange: This event is fired before the value of the observable is changed. The callback function will receive two arguments: the current value of the observable and the proposed (new) value that will be assigned to the observable. This allows you to perform actions based on the current value before it is changed;
  3. afterChange: This event is triggered after the value of the observable is changed. The callback function will receive two arguments: the previous value of the observable (before the change) and the new value that was assigned to the observable. It's useful when you need to react to a specific change after it has occurred.
  4. arrayChange: This event is specific to Observables Arrays. It is triggered when there is a change to an observable array, such as adding, removing, or replacing items in the array. The callback function takes four arguments: the affected items (added, deleted, status and index).

Another important point is that it is possible to store the subscription in a variable and, if necessary, cancel the subscription using the dispose() method. This is useful when you want to temporarily or permanently disable UI updating in response to changes in observables.

let myObservable = ko.observable(0);

// Criando uma subscription no observable
myObservable.subscribe(function (newValue) {
  console.log('Novo valor do observable:', newValue);
}, scope, event);
Copy after login
Copy after login
Copy after login

Methods for determining types of observables

  1. isObservable(): This method is used to check if a value is an observable. It returns true if the value is a observable (observable, observableArray, computed or writable computed), and false otherwise.
  2. isWritableObservable(): This method checks if a value is a writable observable (writable observable). It returns true if the value is a writable observable and false otherwise;
  3. isComputed(): This method is used to check if a value is a Computed Observable. It returns true if the value is a Computed Observable and false otherwise;
  4. isPureComputed(): This method checks if a value is a Pure Computed Observable. A Pure Computed Observable is one that depends only on other pure observables and has no internal recording logic. It returns true if the value is a Pure Computed Observable and false otherwise.

Observable Arrays

Observables Arrays are an extension of observables and are used to deal with lists of data that need to be observable. Unlike a standard JavaScript array, an Observable Array allows you to automatically track changes to list data and update the user interface reactively.

let myObservable = ko.observable('Inicial');

console.log(myObservable()); // Irá imprimir 'Inicial'

myObservable('Novo valor');
console.log(myObservable()); // Irá imprimir 'Novo valor'
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Observables Arrays have specific methods that allow you to add, remove and manipulate items reactively. Some of these methods are:

  • indexOf(value): Returns the index of the first item of the array that is equal to its parameter, or the value -1 if no matching value is found.
  • push(item): Adds a new item to the end of the array;
  • pop(): Removes and returns the last item from the array;
  • shift(): Removes and returns the first item from the array;
  • unshift(item): Adds a new item to the beginning of the array;
  • remove(item): Removes a specific item from the array;
  • removeAll([parameter]): Removes all items from the array, and can receive a parameter in the form of array that will remove the items within the passed parameter(s);
  • replace(oldItem, newItem): Replaces the item passed in the first parameter with the second parameter;
  • reverse(): Changes the order of items in the original array and updates the user interface to reflect the new order;
  • reversed(): Returns a reversed copy of the array;
  • splice(index, count, items): Allows you to add or remove items in a specific position in the array;
  • slice(): Returns a copy of a subset of the array, starting at the start index and going to the end-1 index. The start and end values ​​are optional, and if not provided;
  • sort(): Determines the order of items. If the function is not provided, the method sorts the items in ascending alphabetical order (for strings) or in ascending numerical order (for numbers);
  • sorted(): Returns a copy of the sorted array. It is preferable to the sort() method if you need to not change the original observable array, but need to display it in a specific order;

For functions that modify the contents of the array, such as push and splice, the KO methods automatically trigger the dependency tracking mechanism so that all registered listeners are notified of the change and your interface is updated automatically, which means there is a significant difference between using KO methods (observableArray.push(...), etc) and native JavaScript array methods (observableArray() .push(...)), since the latter do not send any notification to array subscribers that their content has changed.

While it is possible to use subscribe and access an observableArray like any other observable, KnockoutJs also provides a super fast method to find out how an array observable did changed (which items were just added, deleted, or moved). You can subscribe to array changes as follows:

let myObservable = ko.observable('Inicial');

console.log(myObservable()); // Irá imprimir 'Inicial'

myObservable('Novo valor');
console.log(myObservable()); // Irá imprimir 'Novo valor'
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Computed Observables

Computed Observables are functions that depend on one or more observables and will be automatically updated whenever any of these dependencies change. The function will be called once each time any of its dependencies change, and any value it returns will be passed to the observables, such as UI elements or other computed observables .

The main difference between Computed Observables and Observables is that Computed Observables do not directly store a value; instead, they rely on other observables to calculate their value. This means that the value of a Computed Observable is always automatically updated when any of the observables that it depends on are modified.

let myObservable = ko.observable(0);

// Criando uma subscription no observable
myObservable.subscribe(function (newValue) {
  console.log('Novo valor do observable:', newValue);
}, scope, event);
Copy after login
Copy after login
Copy after login

Methods of a Computed Observable

  1. dispose(): This method is used to dispose (clean up) a Computed Observable when it is no longer needed. It removes all subscriptions and dependencies associated with Computed Observable;
  2. extend(): This method allows you to add custom extenders to a Computed Observable. Extenders are functions that can modify the behavior of Computed Observable;
  3. getDependenciesCount(): This method returns the number of observables dependent on the Computed Observable;
  4. getDependencies(): This method returns an array containing the observables that are dependencies of the Computed Observable;
  5. getSubscriptionsCount(): This method returns the number of current subscriptions from the Computed Observable;
  6. isActive(): This method returns a Boolean value that indicates whether the Computed Observable is currently active (a Computed Observable is active if it is in the process of being evaluated due to a change in its dependencies );
  7. peek(): This method is similar to the parenthesis operator () used to access the current value of a Computed Observable. However, the peek method does not create a dependency between the Computed Observable and the place where it is called;
  8. subscribe(): This method allows you to subscribe to receive notifications whenever the value of Computed Observable changes.

this

The second parameter to ko.computed sets the value of this when evaluating the calculated observable. Without passing it, it would not be possible to reference this.firstName() or this.lastName().

There is a convention that avoids the need to track this completely: if the constructor of your viewmodel copies a reference to this into a different variable (traditionally called self), you can use self throughout your viewmodel and don't have to worry about it being redefined to refer to something else.

let myObservable = ko.observable('Inicial');

console.log(myObservable()); // Irá imprimir 'Inicial'

myObservable('Novo valor');
console.log(myObservable()); // Irá imprimir 'Novo valor'
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Because self is captured at function closure, it remains available and consistent in any nested function, such as the evaluator of the computed observable. This convention is even more useful when it comes to event handlers.

Pure computed observables

If a computed observable simply calculates and returns a value based on some observable dependencies, it is better to declare it as ko.pureComputed instead of ko.computed.

let myObservable = ko.observable(0);

// Criando uma subscription no observable
myObservable.subscribe(function (newValue) {
  console.log('Novo valor do observable:', newValue);
}, scope, event);
Copy after login
Copy after login
Copy after login

When a computed observable is declared as pure, its evaluator does not directly modify other objects or state, KnockoutJs can more efficiently manage its re-evaluation and memory usage. KnockoutJs will automatically suspend or release it if no other code has an active dependency on it.

Writable Computed Observables

Writable Computed Observables are an extension of Computed Observables that allow the creation of computed observables that can be updated both through reading and writing . Unlike conventional Computed Observables, which only calculate their value based on other observables and do not directly store a value, Writable Computed Observables can store a value and also provide a function to update this value when necessary.

To create a Writable Computed Observable, it is necessary to use the ko.computed function with a configuration object that contains two main properties: read and write. The read property contains the calculation function to determine the value of the observable, while the write property contains the function that is called when you want to update the value of the observable.

The above is the detailed content of How Observables 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template