Question

i read that events can be binded to an element as

$('btn-submit').bind('click', function(){
  // your custom code
});

and in another way as,

$(document).on('click', 'btn-submit', function(){
  // your custom code
});

which is the correct and most efficient way? I am using rails 3.

Was it helpful?

Solution

The first one is using to bind event that are present in DOM at the time of binding and is called Direct Binding whereas second one is Event Delegation is required when elements are not present at the time of binding event but added later on.

Direct and delegated events

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

Reference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top