0

How does one discover which Javascript events exist in Magento 2?

I need to run some Javascript code in an adminhtml form for a custom module. The code should run after the fields are displayed (i.e. the spinner disappears). Is there a Javascript event that runs at that time? Or should I just check the existence of the target field with setInterval?

1 Answer 1

1

Magento doesn't provide any specific JS events for full rendered form or specific elements. You can try to play with contentUpdated, but i guess better to use setInterval

// $ is jQuery
/**
 * @param {string} selector
 * @param {CallableFunction} callback
 * @param {null|$} context
 */
function waitForElement(selector, callback, context) {
    var startTime = Date.now(), checkFrequency = 500, timeout = 10000;
    if (typeof context === 'undefined') {
        context = $('document');
    }
    (function loopSearch() {
        if (context.find(selector).length > 0) {
            callback();
            return;
        } else {
            setTimeout(function () {
                if (timeout && Date.now() - startTime > timeout) {
                    return;
                }
                loopSearch();
            }, checkFrequency);
        }
    })();
}

// using like
waitForElement(selector, function(){});
waitForElement(selector, function(){}, $(parentSelector));

Alternative is using uiRegistry

// uiRegistry is uiRegistry
uiRegistry.get('index = field_name', function () {
    // custom logic
});

See more examples in doc uiRegistry

Also you can use $.Deferred() and $.when(...).then(...)

Your Answer

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

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