I`m trying to load a custom script after a custom-template for minicart items is rendered.
I created a javascript file vendor\module\view\frontend\web\js\test.js
:
define('jquery', function($) {
alert('Here');
});
and added it to my requirejs-config.js
:
var config = {
map: {
'*': {
'Magento_Checkout/template/minicart/item/default.html':
'Vendor_Module/template/minicart/item/default.html',
test: 'Vendor_Module/js/test'
}
}
};
No I try to run it after the rendering in my default.html with:
<div class="test" afterRender="test"></div>
But the console just outputs:
test is not defined
I really would appreciate any help on this. Why is the script not loaded?
For clarification: Vendor and Module are of course placeholders here.
Best Answer
The
afterRender
method calls the specified method (test
) of your component. So for your case you must define thetest
method inside the minicart component. You must add a mixin for thevendor/magento/module-checkout/view/frontend/web/js/view/minicart.js
and add thetest
method or completely change the renderer component to define a new method. Here is simple example with overwriting a renderer component in custom module:Here is complete code of example on GitHub.
Set custom template and custom component where we can define out
test
method:Update regular template (add a custom
div
withafterRender
binding):Define the component having
test
function (we just logging a dummy string inside):Here is output on the frontend with 2 items added in minicart:
Here is some clarification for "why test is not defined" error from your example:
When you put the
test
method in theafterRender
binding inside template, the ko calling some anonymous function which binds an actual context and trying to call method you pass:An actual context in that case (item renderer in cart) is
Window
which has no method test:The
$parent
for this context is our component:Another available parents could be seen using the
$parents
keyword and we can access them using$parents[n]
call inside theafterRender
binding. The$data
variable has all data about current cart item: