Rails Ajax event on replaced DOM element

394 views Asked by At

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.

1

There are 1 answers

0
Int'l Man Of Coding Mystery On

When I've had remote links, to something like a posts show action, I would create a show.html.erb for the normal interactions, then also create a show.js.erb where there I would target the element I wanted changed/modyfied from the remote link and use the escape javascript method to replace the html there. It would look something like $('some element').html('<%= j render 'some_partial.html.erb'%>'). Where some_partial.html.erb would be the partial of the element that's being replaced.

Escape Javascript