Thursday, May 5, 2011

jQuery mulitple click handlers..how to ensure order of firing?

I have 2 click handlers binded to an element like so:

in the file which contains the control I am binding to, I have the first handler, which does some functionality specific to that control

$("#mycontrol").live("click", function() { alert("foo"); });

In the main page which uses that control, I have another handler binding to that element for page specific functionality

$("#mycontrol").live("click", function() { alert("bar"); });

I use 'live' because AJAX calls are changing the control all the time, so the handlers will be reregistered. However I need a way so that "foo" happens before "bar" consistently...any suggestions?

From stackoverflow
  • How's about:

    $("#mycontrol").live("click", doFooBar);
    
    function doFooBar() {
        alert("foo");
        alert("bar");
    }
    
    puffpio : this won't work because both the control and the main page both contain the live handler..
  • Try combining the click events into one:

    function foo() { alert("foo"); }
    function bar() { alert("bar"); }
    $("#mycontrol").live("click", function(){ foo.call(this); bar.call(this); });
    
    puffpio : i ended up putting a stub JS function in the subcontrol's file..and the click handler calls that after it's own work and in the main page, i override the stub function w/ the page specific functionality
  • You could do something like the following:

    var arrEventHandlers = [];
    
    function registerClickEvent(fnCallback)
    {
        arrEventHandlers.push(fnCallback);
    }
    
    registerClickEvent (function () { alert ("Foo"); });
    registerClickEvent (function () { alert ("Bar"); });
    
    function clickHandler ()
    {
        for (var i = 0, size = arrEventHandlers.length; i < size; i++)
        {
         arrEventHandlers[i].apply (...);
        }
    }
    
    $("#mycontrol").live("click", clickHandler);
    
    puffpio : i like this, but it's overkill for this instance..if i have to do this more time, i think i will go with a solution like this

0 comments:

Post a Comment