cancel
Showing results for 
Search instead for 
Did you mean: 

How to call function after rendering a knockout js template

SOLVED

How to call function after rendering a knockout js template

In checkout, I want to call a function after rendering the email form. Magento provides the "afterRender" attribute on html elements to call a uiComponent function, and this is working. However, I would like to use the "afterRender" property within a uiComponent's default.template property.

 

For example, I want to change this line, to something like this:

defaults: {
    template: {
        name: 'Magento_Checkout/form/element/email',
        afterRender: this.emailHasChanged
    }
}

 The "afterRender" function expects a function to call after rendering the template, just as it does when used in an html template using afterRender="emailHasChanged".

 

The html attribute method of calling a function works, but calling this.emailHasChanged inside my JS file does not. Is there a way that I can call emailHasChanged after rendering the template?

1 ACCEPTED SOLUTION

Accepted Solutions

Re: How to call function after rendering a knockout js template

I will answer my own question.

defaults: {
    template: {
        name: 'Magento_Checkout/form/element/email',
        afterRender: function (renderedNodesArray, data) {
            data.emailHasChanged();
        }
    }
}

However, I will caution anyone from actually using this solution. Using the "afterRender" method like this may produce unintended results because the DOM elements may not actually be rendered by the time your function is called. You may also experience your function being called multiple times.

 

Moral of the story, stick to using the Magento provided "afterRender" template binding by adding it to your html elements like so:

 

<div afterRender="myFunctionFromViewModel">...</div>

View solution in original post

1 REPLY 1

Re: How to call function after rendering a knockout js template

I will answer my own question.

defaults: {
    template: {
        name: 'Magento_Checkout/form/element/email',
        afterRender: function (renderedNodesArray, data) {
            data.emailHasChanged();
        }
    }
}

However, I will caution anyone from actually using this solution. Using the "afterRender" method like this may produce unintended results because the DOM elements may not actually be rendered by the time your function is called. You may also experience your function being called multiple times.

 

Moral of the story, stick to using the Magento provided "afterRender" template binding by adding it to your html elements like so:

 

<div afterRender="myFunctionFromViewModel">...</div>