glortho
glortho

Reputation: 13198

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 follows:

$(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.

Upvotes: 0

Views: 625

Answers (3)

brad
brad

Reputation: 32355

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.

Upvotes: 1

TelegramSam
TelegramSam

Reputation: 2790

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

When I define data, it works as expected.

Upvotes: 1

jwwishart
jwwishart

Reputation: 2895

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();

Upvotes: 0

Related Questions