A plugin as far as I read is created for intercepting a PHP function call and running code before, after, or around that function call. Is there a way how to accomplish that in js file?
How can i intercept Magento 2 module js file function call with another function that is located in another module?
Example: js generates an array and i want to add additional element into that array with another module, before it gets processed by another js function. Similar to what is done in magento checkout customization tutorials but only using js file(s) (adding layout elements dynamically).
PS: Can it be done and if not then why? What might be cons? Sorry if that is against any js patterns or best practices?
Best Answer
You do this with using a requirejs
mixin
and themage/utils/wrapper
js module.Heres a demonstration of how the
wrapper
module functions:In this example,
wrapped1
works like an 'after' plugin, andwrapped2
works like a 'before' plugin. You can combine the two to get an 'around' plugin.For a real world example, here's how to create a plugin for the
collectData
method ofMagento/Ui/view/base/web/js/form/from.js
. We need to use a requirejs 'mixin' to do this.In your module, create the file
Your/Module/view/base/web/requirejs-config.js
:Now make the file
Your/Module/view/base/web/js/plugin.js
:You can read more about
mixins
andwrapper
here: http://alanstorm.com/the-curious-case-of-magento-2-mixins/