Custom event in jQuery that isn't bound to a DOM element? Custom event in jQuery that isn't bound to a DOM element? jquery jquery

Custom event in jQuery that isn't bound to a DOM element?


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) { /* ... */ });


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.


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});