There are various ways to bind events to elements in jquery
.click , .bind, .live, .delegate, saving events data in .data etc
which is the most superior method among these and why?
wouldn’t a single pattern like this be more beneficial?
$('selector').bind({
event: 'click mouseover ...',
keepAlive: (true, false, ...),
trigfunction: (function() {
// I run for click
}, function() {
// i run for mouseover
}, function() {
///...
})
});
I don’t agree that setup would be simpler, because you so rarely bind more than 1 or 2 events to objects, at least in the grand scheme of things…thought it does happen.
.event(func)is a shortcut, it’s equivalent to.bind('event', func)so whatever your preferences is there is all that matters. However you if want want to bind the same handler to multiple events,.bind('event1 event2 event3', func)is much shorter..delegate(selector, event, func)is just.live('event', func)with a context, but of course these behave off bubbling, so they have another use…not necessarily “superior”, just depends on the purpose.It all depends on what you’re trying to accomplish as to which is better. Binding 4,000 elements with
.bind()is a lot less efficient than.live()or.delegate()once. The reverse is true too though,.bind()on a single element (that isn’t replaced via AJAX, etc) is a lot more efficient than having.live()listen for an event that will bubble 20 times. If you’re looping through JSON for example and bindingnitems, this should be a concern, as there is time spent assigning those event handlers.