I have a page with many buttons, many of which I add after the initial jQuery loading, using ajax.
I have some handlers in my script.js
file, here is one:
$('.editor-button.remove').click(function () {
var row = $(this).parent('.row');
row.remove();
});
How can I make sure:
- The handler is always attached to all the buttons satisfying the jQuery selector, even those who were just loaded to the page via ajax
- The handler is not attached zillion times to each element on each ajax call
- What is the general convention to make my entire website handled via jQuery classes instead of inline
onclick
handlers, is this a bad habit? First two questions apply to this one too obviously.
I'm pretty new to event-handling via jQuery concept, I want to keep script.js
as clean as possible not polluting it with localized stuff, in the other hand, I want my buttons to contain only class names, not ciphered functions etc. General rule is my code should be as clean as possible while each handler isn't attached zillion times with each ajax call.
I'm not looking for a solution to the issue I mentioned above, but rather for general guidelines on how to treat jQuery handlers as efficiently and clean as possible.