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.

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

| improve this answer | |
  • 3
    setInterval is not good way for this – Charvi Parikh Jan 18 '18 at 9:41
  • setInterval not guarantee to do a trick all time – Murtuza Zabuawala Dec 17 '18 at 8:05
1

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.

| improve this answer | |
0

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>');
    });
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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