Extending jQuery widget components

Assuming we wish to extend the redirectUrl component instead of replacing it completely, we can do so in a similar fashion. The entry in our requirejs-config.js remains the same, whereas the difference lies in how we edit our redirect-url.js file:

define([
'jquery',
'jquery/ui',
'mage/redirect-url'
], function ($) {
'use strict';
$.widget('magelicious.redirectUrl', $.mage.redirectUrl, {
/* Override of parent _onEvent method */
_onEvent: function () {
// Call parent's _onEvent() method if needed
return this._super();
}
});
return $.magelicious.redirectUrl;
});

Using the _super or _superApply is a jQuery widget way of invoking methods of the same name in the parent widget. While this approach works, there is a more elegant solution called mixins.

The Magento mixins for JS are much like its plugins for PHP. To convert to the mixin approach, we replace our requirejs-config.js with content, as follows.

var config = {
config: {
mixins: {
'mage/redirect-url': {
'Magelicious_Jsco/js/redirect-url-mixin': true
}
}
}
};

Note, that this time we are using the full path 'mage/redirect-url' instead of the redirectUrl alias on the left side of the mapping, whereas the right side of mapping points to our mixin. The convention is to use the -mixing suffix on top of the original JS filename.

We then create <MODULE_DIR>/view/frontend/web/js/redirect-url-mixin.js with content, as follows:

define([
'jquery'
], function ($) {
return function (originalWidget) {
$.widget(
'magelicious.redirectUrl',
originalWidget, {
/* Redefined _onEvent method */
_onEvent: function () {
console.log('_onEvent via mixin'),
// Call parent's _onEvent() method if needed
return this._super();
}
}
);
return $.magelicious.redirectUrl;
};
});

The example here might not do justice, as it merely looks more complex than the previous example of directly extending the widget. This is because we cannot simply do originalWidget._onEvent = function () { /* ... */ }; or originalWidget._proto._onEvent = function () { /* ... */ }; and thus override the widget method. Widget methods need to be overridden on the prototype, which, in our case, essentially means creating a new widget from the original.

If we were adding a mixin for a non-widget type of JS, such as Magento_Checkout/js/action/place-order, then the approach would be different, as shown in Magento_CheckoutAgreements/js/model/place-order-mixin .

..................Content has been hidden....................

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