How Magento initializes & bootstraps Knockout.js
Let’s now explore how Magento initializes and bootstraps Knockout.js, which is different from the standard initialization process. Magento bootstraps Knockout.js within the Magento UI module, so we will start by looking at the module-ui folder within the vendor folder.
Magento UI Module Structure
Navigate to the following path:
view/base/web/js/lib/knockout/bootstrap.js
From the comments, we can see that it loads all available Knockout bindings, sets a custom template engine, and initializes Knockout. Scrolling down the code, it sets a “uid”, a custom template engine, and then calls ko.applyBindings()
. The main purpose of this template engine is to make Knockout look for components on the page using Magento template syntax. This makes it possible to look up Knockout templates based on a special string syntax.
Locating the Knockout Library
Next, let’s find where “ko” comes from, which is the Knockout library. We see a “ko” alias here, but where is this actually defined? Navigate to the Magento Theme module, which is at vendor/module-theme
, and then go to view/base/requirejs-config
. If we look through this file, we can see an alias set at the top for “ko”, and this maps to knockoutjs/knockout
.
During the fallback process of looking for RequireJS dependencies, it will fall all the way back to the lib/web
folder. So if we go back to the root of our Magento install, and then go to lib/web/knockoutjs/knockout.js
, this is the actual version of Knockout that is used in Magento. And this is how we can also tell that it’s using version 3.4.2.
Examining the Bootstrap.js File
Returning to the bootstrap.js
file, note how there are a few files imported here, but they’re not referenced in the function callback. This is how Magento and RequireJS handle other initialization processes. You can include it, and not reference it in the callback, but the code is still loaded and executed.
Let’s look at the bindings/bootstrap
file. If we scroll down in this file, we can see that an object is returned that defines all of these custom Knockout data bindings. All these do is require a specific file and return it in an object property. If we look at a specific example here, for example “fadeVisible”, we can see that each of these files calls ko.bindingHandlers
, and then sets a new property on that object. And this is where the custom data binding is coded up.
Custom Data Bindings
You will learn more about these custom data bindings later in the course, but just know that this file is loaded and returned as an object property. And that’s how these data bindings get initialized.
Using Knockout in Magento
Now that we know how the entire Knockout.js process is initialized in Magento, we can just call the “ko” alias within our own “require” or “define” functions to use the Knockout library.