JJK
JJK

Reputation: 179

Custom events in jQuery

I'm trying to utilize jQuery's custom events. On DOM load I bind body to a custom event test using $.on(). Immediately after, I fire that event and everything runs as planned. However, any other time I fire the event (on a callback, from the console, etc.), nothing happens. I've written a jsfiddle to illustrate this situation. Any ideas?

$(function(){
    $('body').on('test', function(){
        alert('test triggered'); 
    });
    $('body').on('click', '.btn', triggerTest);
    $('body').trigger('test');    
});

var triggerTest = function(){
    $('body').trigger('test');
}

http://jsfiddle.net/vgEzD/

Upvotes: 0

Views: 1017

Answers (1)

Šime Vidas
Šime Vidas

Reputation: 185893

Your order is wrong. This works:

var triggerTest = function(){
    $('body').trigger('test');
}

$(function(){
    $('body').on('test', function(){
        alert('test triggered'); 
    });
    $('body').on('click', '.btn', triggerTest);
    $('body').trigger('test');    
});

Live demo: http://jsfiddle.net/simevidas/vgEzD/3/

Apparently jQuery executes the DOM ready handler immediately and at that point, the triggerTest function isn't assigned yet. So, I you want to create globals, do that above the ready handler.

Btw, in your jsFiddle, "onLoad" execution is set. This means that the JavaScript code is executed on window "load", and at that point DOM ready has already occurred which is why jQuery executes the code immediately.

Upvotes: 2

Related Questions