Custom event in jQuery that isn't bound to a DOM element?
Solution 1:
You can trigger custom global events like this in jQuery:
jQuery.event.trigger('mycustomevent', [arg1, arg2, arg3]);
These will trigger for any element.
Since jQuery is built around DOM objects, you have to bind your events to DOM objects. You can probably find some way to bind events without an element too (you did), but that's not a supported methodology.
As you wrote in your own answer, you can bind your event to a global DOM object if you don't want to bind it to an individual page element:
$(document).bind('mycustomevent', function (e, arg1, arg2, arg3) { /* ... */ });
Solution 2:
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.
Solution 3:
For future readers, its fairly simple to do this. I did further research after posting my question. Unfortunately none of the other commenters were correct.
In order to bind a custom event:
$().bind('mycustomevent', function(){
//code here
});
Also, you can build data into the event object that is later accessible:
$({mydata:'testdata'}).bind('mycustomevent',function(){
//code here
});
Solution 4:
Binding to non-dom elements has been removed in jQuery 1.4.4.
Solution 5:
You can still arbitrarily trigger and respond to events using jQuery, even if you don't know what element to attach them to. Just create a "receiver" element in your document, to which you can bind all your custom events. This allows you to manage your event handling logic in one place, for all your non-element-specific events.
$(document).ready(function() {
$(body).append('<div id="receiver">');
$("#receiver").bind("foo_event", function () {
// decide what to do now that foo_event has been triggered.
});
$("#some_element").click(function() {
$("#receiver").trigger("foo_event");
});
});