What is Knockout.js?
Knockout.js is a way to build dynamic components with user interfaces similar to React or VueJS. If you’re familiar with those frontend UI frameworks, the premise is that data is bound directly to an HTML DOM element. When the data changes, the HTML will automatically react to those changes. Knockout is considered a Model-View-ViewModel (MVVM) architecture, just like Magento, making it a great match.
Understanding MVVM Architecture
In the MVVM architecture, the view is a presentation layer and usually consists of an HTML file containing all the HTML elements you wish to display on the page. It deals just with the appearance and presentation of the display, so it usually doesn’t contain any business logic.
ko.applyBindings() is what registers this view model as a Knockout.js component.
Finally, the model consists of any variables, observables, or other data that is either hard-coded or retrieved from an API. The view consists of the presentation logic, the model is the underlying data, and the view model ties the model back to the presentation layer.
Knockout.js Version in Magento
The current version of Knockout is 3.5.1, but the version used in Magento is 3.4.2. There aren’t many differences between the two versions, but it’s good to know what version you’re on to understand the functionality you have access to.
Knockout.js Example in Magento
Magento uses UI components in combination with Knockout. UI components add some additional functionality and the ability to more easily debug these components. You can think of UI components as a wrapper around Knockout.
The code within
component.extend() would be considered the view model. The model contains variables such as the
isLoading variable. The view model contains separate functions that just do things and make the view react to the data that is changing within these functions.
Best Practices with jQuery
It’s important to note that the view model should not contain any jQuery, which is considered a good practice. The switch from jQuery to Knockout is quite the paradigm shift, and you typically choose one or the other. You don’t use both because jQuery will manually make changes to the DOM elements, while Knockout will dynamically change those DOM elements based on a reactive value.
The exception in Magento is jQuery widgets, which are used in combination with Knockout. This approach is acceptable because most of the logic in jQuery widgets is self-contained and not intermingled in Knockout.
However, Magento core code sometimes imports jQuery and uses it within the UI components. This should generally be considered a bad practice. When you have pieces of code that run jQuery to manually manipulate the DOM and other areas of code which use Knockout to dynamically re-render changes, it will lead to a mess of spaghetti code. While jQuery has its time and place, integrating it with Magento’s Knockout implementation should be avoided.