Reputation: 9672
I know I can assign an event handler to an html element or class so that if new elements are loaded dynamically the event will still fire to the new added elements. For example:
$('#main').on('click','a.link_class', function () {
// ...
});
I have elements to which I apply a plugin function and then contain those in an array. Then I need to assign an event to this array elements (specifically to them,not to a class they have in common). Is there any way to do this avoiding using for loop or each() (so that new elements added lately to the array still fire with the event)? A simple way like the above example? Something like:
$('#main').on('plugin_event',array, function () {
// ...
});
or...
$('#main').on('plugin_event',array[i], function () {
// ...
});
Upvotes: 1
Views: 435
Reputation: 263047
You will have to keep track of the array, and check in your handler that the current event target is present in that array.
You can use data() to achieve the former:
$("#main").data("plugin-array", yourArray);
You can then implement the latter with $.inArray():
$("#main").on("plugin_event", function(e) {
if ($.inArray(e.target, $(this).data("plugin-array")) >= 0) {
// Target element is present in the array, handle the event...
}
});
Upvotes: 2
Reputation: 663
When initially creating the array you could instead add a unique CSS class to each of them. This would allow you to use a jQuery selector to return all the elements and bind the additional behavior to them all at once.
If you need to add or remove elements from the array you could add or remove the class from the elements. You can cache the results of the jQuery selector for similar performance to the array you're using.
Upvotes: 0