Sunday 3 January 2021

Rails Ajax event on replaced DOM element

I have a simple Rails ujs app, with some remote links on the page.

<%= link_to 'Test', posts_path, remote: true, id: 'test' %>

In my js template, I replace this link with new one.

$('#test').html('<%= j link_to "Test", posts_path, remote: true, id: "test" %>')

At the same time I need to listen to ajax:success event:

window.addEventListener("load", () => {
  document.body.addEventListener("ajax:success", (event) => {
    # => Expected to be fired on all success ajax calls, no matter partial dom manipulations
  });
});

But the problem is that this event never fires. Because its target element get replaced.

How can I listen to ajax:success even if its target element is removed from dom?

My code has no practical sense, but its purpose is to demonstrate realworld problem in simple way.



from Rails Ajax event on replaced DOM element

No comments:

Post a Comment