Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top