Knockout - Magento 2
Paboda Hettiarachchi
Posted on November 14, 2020
I always found it difficult when it comes to a JS implementation in Magento 2. Reasons geing not experienced in Knockout JS scope and had a general fear and confusion in ES6/jQuery/Knockout combined together.
I'm trying to break the barrier here as I needed to be perfectly clear on the concepts.
As inline script is not the proper standards, we normally have a phtml and a js file included. In some cases we need to use html file as well.
exampleone
exampleone.phtml
<div id="one"><?= "TESTING" ?></div>
<script type="text/x-magento-init">
{
"#one": {
"Paboda_LearnKo/js/exampleone":{}
}
}
</script>
exampleone.js
define([], function(){
var mageJsComponent = function()
{
console.log('hello...');
};
return mageJsComponent;
});
As using script tags in phtml is not considered, data-mage-init should be used in the html instead
<div id="one" data-mage-init='{"Paboda_LearnKo/js/exampleone": {}}'><?= "TESTING" ?></div>
exampletwo - data-bind with scope
exampletwo.phtml
<div data-bind="scope: 'text-binding'">
<div><?= "Scope Binding" ?></div>
<div id="main">
<h1 data-bind="text: sayHello"></h1>
</div>
</div>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"text-binding": {
"component": "Paboda_LearnKo/js/exampletwo"
}
}
}
}
}
</script>
exampletwo.js
define([
'uiComponent'
], function(Component) {
return Component.extend({
initialize: function () {
this._super();
this.sayHello = "This is the binding text from KO...";
},
});
});
examplethree - data-bind with scope in html template
examplethree.phtml
<div data-bind="scope: 'text-binding'">
<div><?= "Scope Binding" ?></div>
<!-- ko template: getTemplate() --><!-- /ko -->
</div>
<script type="text/x-magento-init">
{
"*": {
"Magento_Ui/js/core/app": {
"components": {
"text-binding": {
"component": "Paboda_LearnKo/js/examplethree",
"template" : "Paboda_LearnKo/examplethree"
}
}
}
}
}
</script>
examplethree.js
define([
'uiComponent'
], function(Component) {
return Component.extend({
initialize: function () {
this._super();
this.sayHelloFromTemplate = "This is the binding text from KO template...";
},
});
});
examplethree.html
<div id="main">
<h1 data-bind="text: sayHelloFromTemplate"></h1>
</div>
examplefour - show html as in data-bind but with data-mage-config
examplefour.phtml
<div id="countdown" data-mage-init='{"Paboda_LearnKo/js/example4": {}}'></div>
examplefour.js
define([
'jquery',
'Magento_Ui/js/lib/core/storage/local'
], function ($, storage) {
'use strict';
return function (config, element) {
let showHtml = function () {
$(element).html(
"test"
);
}
showHtml();
};
});
Posted on November 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
April 18, 2024