Listen to specific OC backend ajax executions

Hello,

Is there any way to listen to specific OC backend ajax executions?

I need to execute some JS after create or update plugin backend page and new repeater item is rendered.

I now do it with a PerformanceObserver. It works, but it’s quite roundabout…

One way of doing it is by using global ajax events: JavaScript API - October CMS - 2.x

$(document).ajaxSuccess(function(event, context, data, status) {
    if(context.handler === "formFields::onAddItem") {
        console.log('A new repeater item has been added');
    }
});

The code above works in October v3 as well, but now it’s also possible to do it in vanilla javascript: JavaScript API - October CMS - 3.x

addEventListener('ajax:request-success', function(event) {
    if(event.detail.context.handler === "formFields::onAddItem") {
        console.log('A new repeater item has been added');
    }
});

You can also attach events to a specific HTML element if you don’t like the global approach.

2 Likes

Thanks for the input! This works really well for adding new repeater item.

But when I go from the list to the form, I didn’t found an ajax request to trigger my already added repeater items.

I guessed this one could work:

addEventListener('ajax:request-redirect', function(event) {
    console.log({ event });
});

But it isn’t triggered on redirect.

Do you have an idea on how to achieve that?

I found a workaround:

I’ve put my repeater listener and all belonging JS functions into the plugin’s assets. Then I’ve added a JS script asset into my FormWidget, which is inside my repeater. So every time my backend form is rendered, the JS in the FormWidget gets set and the functions inside my plugin’s assets get executed.

Of course I check, if the functions in my plugin’s assets are there and call it in the FormWidget JS like this:

if (typeof myFunction === "function") {
        myFunction();
}