Reputation: 12670
I'm stuck with some jQuery-based library which is forcing me to add an attribute to a lot of elements in my markup in order for it to "unobtrusively" do some AJAX posting of forms for me, as if they haven't yet looked in a dictionary to read up on what "unobtrusive" actually means.
After trying to poke at said library from the outside to change the selector it was using, I gave up on that and am now trying to use jQuery to add the attribute so that I can make it actually-unobtrusive.
If I do this:
$('form.filter, .pagination a, .sortable a').attr('data-remote', true);
This fixes every element at the time of execution. The problem is that the AJAX queries replace sections of the page which then contain more elements which should have the attribute added. So I'm finding that the first click works, but the second loads the page without using AJAX, at which point the cycle repeats because the whole document has been loaded again.
I vaguely gather that on()
is for this sort of thing, but I have tried multiple ways of using it and none of them have fired yet (I have an alert
in there so that I would find out when it does.)
What is the proper way to do this?
Upvotes: 0
Views: 349
Reputation: 6025
Your best bet is to find the success callback of the form posting and include your attribute assignment there. You can also use the global ajax success callback as Floris has stated by adding
$(document).ajaxSuccess(function() {
$('form.filter, .pagination a, .sortable a').attr('data-remote', true);
});
Upvotes: 2
Reputation: 219920
Unfortunately, .on()
won't help here. That's only helpful for event delegation.
You should probably just bite the bullet and include the attributes directly.
If you insist, you can use DOM Mutation Observers for this.
For older browsers, you'll have to use the older DOM Mutation Events, which have now been deprecated.
For an explanation of those two methods, read this article:
Detect DOM changes with Mutation Observers.
Upvotes: 2