开发者

Why can't I fire custom events?

I'm trying to fire custom events using jquery but for some reason I can't seem to fire and/or capture them.

I'm using a jstree plugin to create a file system with folders:

$('.filetree.global, .filetree.workspace').bind('select_node.jstree', function (event, data) {
    alert('test ');
    $(document).trigger( 'filePick').trigger( 'folderPick' );
}).jstree({
    /*stuff*/
});

Further down the code I'm binding the filePick and folderPick events to elements with a specific class and tell them to alert a test message whenever they c开发者_Go百科atch the event:

$('.folder-action').bind( 'folderPick', function(e, data) {
    alert('test 2');
} );

Unfortunately the alert never gets triggered and I don't know why. The jquery documentation seems pretty clear to me and I followed a different tutorial which also seems to indicate that my code should work but it just isn't! ARGH!

'test 1' gets alerted but not 'test 2'. Also, I installed Eventbug (Firebug extension) and I can see that my bindings to filePick are registered which leads me to believe that filePick and folderPick are just never fired.


jQuery events bubble up, but not down. This means that when you trigger the event on the document, it will not trigger down to elements inside the document. You can either trigger the event on that element, or trigger the event globally.

To trigger on that element, do this:

$('.folder-action').trigger( 'folderPick' );

To trigger the event globally so all subscribed elements get the event, do this:

$.event.trigger( 'folderPick' );


this is because you try to trigger the event on the document you need to do:

$('.folder-action').trigger( 'folderPick' );

and not:

$(document).trigger( 'folderPick' );

for example. When you bind the event, you bind it on a DOM element. When you want to call it again you need to select that same DOM element... Or trigger the event globally like in Dan Herberts example.

If you don't want this, simply make a function


You are triggering the custom events on document but have bound an event listener for custom events to .folder-action.

DOM Events

  1. go down the DOM (capture phase) until
  2. they reach the target (at target) then
  3. bubble up (bubbling phase) the DOM.

but jQuery custom events

  1. trigger at the target (at target) then
  2. bubble up (bubbling phase) the DOM.

So when the custom event is raised, it will be raised at document then bubble up, thereby never being raised on .folder-action, hence the alert is not firing.

You either need to bind your event listener for the custom event on document or trigger them on .folder-action. An example of binding on document.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜