3 ms·
I think there's a better approach to handling the delete buttons that's pretty common when using jQuery. Instead of each button having it's own handler function
by jasonkostempski 10y ago
I think there's a better approach to handling the delete buttons that's pretty common when using jQuery. Instead of each button having it's own handler function I would specify an event handler on a single DOM element (e.g. a list container) with something like $('#itemlist').on('click', '.delete', deleteItem). When 'deleteItem' is called 'this' will be the clicked button element that could have an attribute like 'data-itemid=123' which you use to fill in the 'id' part of the service call. And from there, after a successful service call, you can usually get at the parent element you want to remove from the list and take just that out instead of refreshing the entire list.
EDIT: Had the 'on' parameters mixed up. Here's the api doc: https://api.jquery.com/on/ https://api.jquery.com/on/
- nicolasMLV 10y agoyes, that is event delegation : https://learn.jquery.com/events/event-delegation/ https://learn.jquery.com/events/event-delegation/
- pcote 10y agoI almost went down the event delegation route. The only thing that stopped me was having stumbled upon a tactic that happened to work where I just attached individualized event handlers one at a time. I appreciate the input and will make sure to give event delegation a second look.