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

JqueryEvents

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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 - Jquery

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 - Jquery

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 - Jquery

Binding to non-dom elements has been removed in jQuery 1.4.4.

Solution 5 - Jquery

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

});

Solution 6 - Jquery

jQuery Callbacks provides a simple way to implement a pub-sub system independent of the DOM.

Near the bottom of the linked page is example code that shows how to do that.

Solution 7 - Jquery

[EDIT]

Here's a working class that uses the concepts written below:

https://github.com/stratboy/image-preloader

It's just a sequential image preloader. You can subscribe to a bunch of events. Take a look.

[/EDIT]

Old post:

Here's another barebones example with callbacks like suggested by Himanshu P.

I'm building a class and I come from Mootools, where things like Classes and custom events directly implemented in classes (so not bound to DOM elements) are absolutely natural. So I tried a sort of workaround and share below.

  var step_slider;

  //sandbox
  ;(function($) {

//constructor
var StepSlider = function(slider_mask_selector,options) {
	
	//this.onStep = $.Event('step');
	this.options = null;
	this.onstep = $.Callbacks();
	
	this.init();
}//end constructor

StepSlider.prototype = {

	init:function(){
		this.set_events();
	},//end init
	
	set_events:function(){
	
		if(this.options){
			if(this.options.onstep){
				this.subscribe('step',options.onstep);
			}
		}

	},//set_events
	
	subscribe:function(event,action){
		this['on'+event].add(action);
	},
	
	fire_onstep:function(){
		this.onstep.fire({ data1:'ok' });
	}
	
}//end prototype/class

//--------------------

$(document).ready(function() {
	
	step_slider = new StepSlider('selector');
	
    //for example, say that you have a div#next-button, you can then do this:
	$('#next-button').click(function(){
		step_slider.fire_onstep();
	});
	
});//end domready


})(jQuery);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeuisView Question on Stackoverflow
Solution 1 - JqueryBlixtView Answer on Stackoverflow
Solution 2 - JquerysbichenkoView Answer on Stackoverflow
Solution 3 - JqueryGeuisView Answer on Stackoverflow
Solution 4 - JqueryTheBentArrowView Answer on Stackoverflow
Solution 5 - JqueryMatt HowellView Answer on Stackoverflow
Solution 6 - JqueryHimanshu PView Answer on Stackoverflow
Solution 7 - JqueryLuca ReghellinView Answer on Stackoverflow