开发者

Custom JQuery event firing in one place but not another

This is probably just my own ignorance of how events work, but can someone explain this: A custom event will not fire at the top of a function, but will fire in a callback inside that function.

The following works (the custom event fires):

function foo() {

    $.ajax( ... , function() {
            $.event.trigger("custom" , data );
    });

}

foo();

The following does not work (the custom event does not fire):

function foo() {
    $.event.trigger("custom" , data );

    $.ajax( ... , function() {
            ...
    });

}

foo();

The event binding is as foll开发者_JS百科ows:

$(document).bind("custom custom1 custom2" , function( event, data ) {
    ...
});

I really want it to fire right at the top of the function. Any help is most appreciated!

NOTE: It's the same issue across browsers, and with or without the extra data argument.


The fact that it works in the async callback leads me to believe that when foo(); is called, the actual binding hasn't taken place. You need to be careful about the order of things when you do this.

jwwishart's answer probably works because he's binding first... then calling foo. If you post the whole code with the order of where things happen though it might be easier to debug.


data appears to be undefined in your second (non-working) method.

When I define data, it works as expected.


The following works... ?

I only bound the "custom" even, I removed the other two (to get things as simple as possible.)

$(document).bind("custom" , function( event, data ) {
    alert(data);
});


function foo() {
    $.event.trigger("custom" , "Works" );
}

foo();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜