Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

events

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 I like, which is creating custom events and being able to subscribe to them later.

For example, this creates an event that is bound to a variable, not to a DOM element:

var myevent = new YAHOO.util.CustomEvent("mycustomevent"); 

All of the examples and documentation I have been reading for jQuery require something like:

$('body').bind('mycustomevent', function(){     //do stuff }); 
like image 467
Geuis Avatar asked Oct 12 '09 08:10

Geuis


1 Answers

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) { /* ... */ }); 
like image 63
Blixt Avatar answered Oct 06 '22 12:10

Blixt