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.
When I've had remote links, to something like a posts show action, I would create a
show.html.erbfor the normal interactions, then also create ashow.js.erbwhere 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'%>'). Wheresome_partial.html.erbwould be the partial of the element that's being replaced.Escape Javascript