search
HomeWeb Front-endJS TutorialHow Observables work in KnockoutJs

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'
  • 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'
  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);

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'

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'

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);

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'

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);

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!

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment