Knockout.js in Magento 2

- Magento 2

Magento 2 Knockout.js

Knockout is a standalone JavaScript implementation of the MVVM pattern which incorporates a clear separation between view components, domain data, and data to be displayed. Besides, it relies on a clearly defined code layer aimed to manage the relationships between all view components. Below, we discuss how Knockout.js is used in Magento 2.

Knockout.js offers the following features: Declarative bindings; Dependency tracking; Automatic UI updates; and Templating.  Being a pure JavaScript library, it supports all possible server or client-side technologies. Knockout.js can be added on top of your existing Magento 2 project without any serious architectural changes. Besides, it is a very compact solution which requires around 13kb. Knockout seamlessly works on any mainstream browser and offers a comprehensive suite of specifications.

In Magento 2, Knockout is utilized within the presentation layer. The MVVM framework streamlines the specification of complex relationships between different view components leading to a better user experience. It uses HTML data bindings for linking model and view. Hence, it is necessary to understand how to create a custom binding from Magento 2. Follow this link – custom bindings that support virtual elements – for further information. To master Knockout.js for simplifying Magento 2 JS UIs via the MVVM pattern, check the official Knockout’s tutorials as well as the official documentation.

Chris Harrington has compared Knockout.JS with React and Angularjs. The results of this comparisons are covered here.

Magento 2 Knockout; Knockout on Firefox

As you can see from the above diagrams, Knockout is the slowest solution, but it still has a lot of benefits and introduces some unique opportunities.

The source code of Knockout in Magento 2 is available on GitHub here: Magento 2 Knockout.  For further information about the project, check this presentation: