Creating jQuery widgets components

Creating simple jQuery widgets components is pretty straightforward from a Magento point of view. The actual knowledge of building robust jQuery widgets depends on our knowledge of jQuery itself.

Let's assume our widget will be called welcome, and its purpose is to simply output Welcome %name% to the element, provided we passed on the name option during widget initialization.

We start by adding the mapping under our <MODULE_DIR>/view/frontend/requirejs-config.js file, as follows:

var config = {
map: {
'*': {
welcome: 'Magelicious_Jsco/js/welcome'
}
}
};

We then define the widget itself, as part of the <MODULE_DIR>/view/frontend/web/js/welcome.js file, as follows:

define([
'jquery',
'mage/translate'
], function ($, $t) {
'use strict';
$.widget('magelicious.welcome', {
_create: function () {
this.element.text($t('Welcome ' + this.options.name));
}
});
return $.magelicious.welcome;
});

We can see that our widget is quite simple. If we now run Magento's setup:static-content:deploy command, our widget should already be ready for use, as we can now initialize it from template files.

Finally, let's initialize our welcome widget by amending playground.phtml, as follows:

<?php $helper = $this->helper('MagentoFrameworkJsonHelperData') ?>

<span data-mage-init='<?= $helper->jsonEncode(
['welcome' => ['name' => 'John Doe']]
) ?>'></span>

With this in place, we should now be able to see the Welcome John Doe message in our browser. While this little component seems quite an overkill for what it does, the concepts behind it are what matters.

See https://api.jqueryui.com/jquery.widget/ for more information on creating jQuery widgets.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.200.226