I\'m curious if its possible to create a custom event in jQuery that isn\'t bound to a DOM element.
I greatly prefer jQuery to YUI but there is one thing in YUI that
According to a comment by John Resig, binding events to custom objects via jQuery is supported:
No particular reason why it's not documented (other than that it's rather non-traditional for most users) - but yes, we support it and have unit tests for it.
So this works:
var a = {foo: 'bar'};
$(a).on('baz', function() {console.log('hello')});
$(a).triggerHandler('baz');
>>> 'hello'
Most users will need triggerHandler()
, not trigger()
. If .trigger("eventName")
is used, it will look for a "eventName" property on the object and attempt to execute it after any attached jQuery handlers are executed (Source).
EDIT (28.02.2017):
After using this pattern for about 2 years in a large codebase, I can attest that this is a bad idea. These custom events lead to incomprehensible data flows. Prefer callbacks instead.