Reputation: 4492
From what I have read, this should work...
$('#test').on "newMessage", ->
alert('test')
$(document).on "newMessage", ->
alert('document')
$.event.trigger('newMessage')
example at http://jsfiddle.net/Nbdyb/
Can someone help me understand why I never get a 'test' alert?
Upvotes: 1
Views: 1002
Reputation: 1916
When I upgrade the jquery
from v1.7.1 to v1.11.1+, I found that $.event.trigger()
doesn't work any more.
Still don't know why, but here is an alternative solution for event-driven operations (not DOM-based event handling):
Old days :
// handler
$(anyElement).on('Foo:SelfDefined:Event', function(event){
console.log( event.self_data_1 );
console.log( event.self_data_2 );
});
------------------
// trigger handler
var evOpts = {
type : 'Foo:SelfDefined:Event',
self_data_1 : 'foo',
self_data_2 : 'bar'
};
$.event.trigger( evOpts );
Now :
// handler
$(document).on('Foo:SelfDefined:Event', function(event, evData){
console.log( evData.self_data_1 );
console.log( evData.self_data_2 );
});
------------------
// trigger handler
var evData = {
type : 'Foo:SelfDefined:Event',
self_data_1 : 'foo',
self_data_2 : 'bar'
};
$(document).trigger(evData.type, evData);
Note: If element A trigger a event, only it's parent node or itself can listen and attach handler to that event, that's why this solution is not good for DOM-based event handling.
Upvotes: 0
Reputation: 4492
Since $.event isn't officially documented, I compared the current source with some older version of jQuery and found a TODO about removing this 'feature'. At least its explained why it doesnt work anymore.
This is the block of code that used to allow this to work.
https://github.com/jquery/jquery/blob/1.6.2/src/event.js#L322-335
The current code now just assigns document
as the element if no element is passed in. Whcih is why it worked fine for document and window.
Looks like I will be needing a separate library if i want anonymous pupsub...
Upvotes: 1
Reputation: 388326
You have a newMessage
handler registered in the #test
element, in order to trigger that the event should be triggered in that element or in one of its decedents(event bubbling).
it should be
$('#test').trigger('newMessage')
Upvotes: 1