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.
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.
dataTo 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'
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'
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);
Methods for determining types of observables
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'
Observables Arrays have specific methods that allow you to add, remove and manipulate items reactively. Some of these methods are:
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'
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);
Methods of a Computed Observable
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'
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.
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);
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 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!