Friday, March 27, 2009

[jQuery] Re: bind to front of event stack

I'm not sure if there's an easy method to alter the event stack in
jQuery, but I can think of a pretty straightforward workaround,
providing you bind the "forcestop" function as the first event
handler.

$('#myTestEl').bind('click.forcestop', function(e){
var el = $(this), force = el.data('forcestop');
if ($.isFunction(force)){
force.apply(this, [e]);
e.stopImmediatePropagation();
}
});

$('#myTestEl').click( function(){ console.log('first event') } );
$('#myTestEl').click( function(){ console.log('second event') } );
$('#myTestEl').data('forcestop', function(e){ console.log('I want to
be first and prevent everyone else from running!'); });
$('#myTestEl').click( function(){ console.log('fourth event') } );
$('#myTestEl').click();

Threw up a public test on:

http://jsbin.com/atahi/edit

Instead of actually binding a click event, you bind the would-be event
handler to the element's data as "forcestop", which the first click
handler in the sequence will detect, trigger, then stopPropagation on.

On Mar 27, 12:24 pm, sliver <sliver2...@gmail.com> wrote:
> Purpose: You have a number of bound events of a specific type to an
> element that are applied depending on specific user interactions.
> However, when one of them is bound, it needs to be fired first and
> then prevent the others from being fired until it has been unbound and
> then return normal behavior for the rest of the bound events. This
> particular bound event could be added to the stack whenever, which
> would could possibly allow other bound events to fire before it.
>
> Example:
>
> $('#myTestEl').click(function() { console.log('first event'); });
> $('#myTestEl').click(function() { console.log('second event'); });
> $('#myTestEl').click(function(e) {
>     console.log('I would like to be first and prevent everyone else
> from running!');
>     e. stopImmediatePropagation();});
>
> $('#myTestEl').click(function() { console.log('forth event'); });
>
> $('#myTestEl').click();
>
> NORMAL OUTPUT:
> first event
> second event
> I would like to be first and prevent everyone else from running!
>
> DESIRED OUTPUT (if could make the third bound function the first to
> fire):
> I would like to be first and prevent everyone else from running!
>
> Then when you unbound the third function the output would be:
> first event
> second event
> third event
>
> I saw an older plugin that added some functionality to the bind method
> to do this... but the last time it was verified was against 1.2.x and
> hasn't been updated since. So, maybe this functionality is now part of
> 1.3.x and I am simply missing it in the docs?

No comments:

Post a Comment