1

I want to add some JS code after KO render all element in page. i have try below code in magento 2.2.2

require(['uiRegistry','domReady!'], function (r) {
        r.get('.test123', function (el) {
            el.append('<a href="javascript:void(0)">Add New</a>');
        });

but this is not working.

3 Answers 3

2

In Knockout js, there is one function called "afterRender" Use that to achieve expected output.

Magento 2.x Doc Link for afterRender binding notifies its subscriber when an associated element is inserted into the DOM.

Sometimes we want to run custom post-processing logic (after DOM ready) on the DOM elements generated by our templates.

For example,

if we're using a JavaScript widgets library such as jQuery UI and want to intercept templates output so that we can run jQuery UI commands on it to transform some of the rendered elements into date pickers, sliders, or anything else.

Generally, the best way to perform such LOGIC's on DOM elements is to write a custom binding,

but if we really just want to access the raw DOM elements emitted by a template, we can use afterRender.

Pass a function reference (either a function literal, or give the name of a function on your view model), and Knockout will invoke it immediately after rendering or re-rendering our template.

For example,

<div data-bind='template: { name: "personTemplate",
                            data: myData,
                            afterRender: applyOurLogicAfterDOMReady }'> </div>

and define a corresponding function on your view model (i.e., the object that contains myData):

viewModel.applyOurLogicAfterDOMReady = function(elements) {
    // "elements" is an array of DOM nodes just rendered by the template
    // You can add custom post-processing logic here
}

If we're using foreach, Knockout will invoke afterRender callback for each item added to our observable array.

1

Try using setInterval like this:-

require([ 'jquery', 'jquery/ui','uiRegistry','domReady!'], function(r){

    setInterval(function () {
        r.get('.test123', function (el) {
            el.append('<a href="javascript:void(0)">Add New</a>');    
        });
    },3000);       
});

Code may require fixes, but the point is to use setInterval

2
  • 6
    setInterval is not good way for this Jan 18, 2018 at 9:41
  • 1
    setInterval not guarantee to do a trick all time Dec 17, 2018 at 8:05
1

Try adding 'ko' to dependencies

require(['uiRegistry','domReady!', 'ko'], function (r) {
    r.get('.test123', function (el) {
        el.append('<a href="javascript:void(0)">Add New</a>');
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.