Skip to content Skip to sidebar Skip to footer

Global Vs. Local Event Handler Binding For Jquery Widget

I try to create a custom widget with jquery with rich functionality, therefore I need custom handlers for many standard events such as dblclick, click, focus, blur etc. I can app

Solution 1:

Using the first form is an easy way to implement the event handler once, but it has extra overhead. The handler is actually invoked for every click on the document, jQuery then has to check whether the target matches the selector; with the second form, the browser only invokes the handler when you click on the specific elements that it's bound to.

The first form can also fail in a subtle way. If there are enclosing elements that have their own click handlers, and they use event.stopPropagation(), this will prevent the event from bubbling up to the document, so the .on() handler will never be invoked.

Regular application developers can mitigate both problems by binding the event to the most deeply nested elements that enclose the dynamic elements they want to delegate to. But a widget developer doesn't have as much knowledge of the context, so it may have to use the wide document scope as in your code. If you can implement the second form, adding the handlers as you add elements to the DOM, that's likely to be better.

One way you may be able to do this easily is by using jQuery's .clone() method. It takes an optional argument indicating whether handlers should be copied. So create a prototype element with the handler bound, then clone it and the new element will also have the handler.

Solution 2:

Well if you have multiple events I would suggest doing this:

$(document).on({
    click: clickFn,
    dblclick: dblFn,
    mouseover: mouseFn,
    ...
}, '.widget-name .element-class');

But to answer your questions:

  1. It all depends on if you want event delegation or if you attaching the event directly to an object on the page
  2. I am not sure

Post a Comment for "Global Vs. Local Event Handler Binding For Jquery Widget"