Suppose I make a global handler for closing a popup :
mouseup_handler: function(item, mouse_is_inside){
if(!mouse_is_inside) {
close_box(item);
return false;
};
},
And I attach it as so :
$("body").bind('mouseup', function(){ mouseup_handler($popup, mouse_is_inside); });
But let’s say I have two objects that the body needs to be responsible for closing.
Now when I call the close of one of the objects :
$("body").unbind('mouseup');
Both, or any mouseup handlers attached to the body are removed. I could be more specific and say :
$("body").unbind('mouseup', mouseup_handler() );
But this would still cause the same problem with all mouseup_handler()‘s to be removed.
How can I allow the body to differentiate between the two ( or many ) yet write the most minimal amount of code that can be shared between the two objects for the same handler?
When the event handler is invoked via jQuery,
thiswill refer to the DOM element involved. Thus:(Or as appropriate; it’s hard to tell because you didn’t post very much code.)
edit wait – if you’re binding to the
<body>but you’re doing it as a delegation thing, you should bind with “on” and not “bind”:By doing that, you ensure that
thisis bound to the actual event target element and not the<body>. The “selector” should identify the actual elements that you’re interested in.To enable and disable event handler behavior, in my opinion it’s much better to do something like add or remove a class name from an element, and to check that in the handler to decide whether to do anything.