0

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/

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
JJK
  • 179
  • 1
  • 2
  • 9
  • 1
    Clicking the anchor throws an error: `TypeError: handleObj.handler.apply is not a function`. The problem is that at the moment you are trying to bind the event handler to the anchor, `triggerTest` is not initialized yet. If I change the fiddle setting to include the code in the `head` of the document, it works fine: http://jsfiddle.net/vgEzD/2/. Why? Because right now you are executing the whole code when the DOM was loaded, i.e. the callback you pass to `.ready` is executed *immediately* before you assign a value to `triggerTest`. – Felix Kling Jun 19 '13 at 23:11

1 Answers1

2

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.

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • Thanks for the help. The answer solves this situation, but not my exact problem. I've asked a slightly more specific question here: http://stackoverflow.com/questions/17203116/jquery-trigger-custom-event – JJK Jun 19 '13 at 23:43