Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use jQuery's event functions with plain old objects?

Tags:

jquery

events

jQuery has functions like .on() and .trigger() that let you attach events to DOM objects and then manually trigger those events. The documentation for these functions specifically refers to events on "elements", which I take to mean HTML/DOM elements.

Can I also use these functions to add event functionality to plain old JavaScript objects?

var x = {};
$(x).on('bonk', function() { alert('Oif!'); });
$(x).trigger('bonk'); // shows the alert

This works in all the browsers I've tested it in (Chrome 15, FireFox 7, IE 9, and Opera 11.52, all on Windows), which seems promising. But it's not clear from the documentation whether it's actually meant to be a supported scenario, in all browsers, on all platforms. The docs' choice of terminology ("elements") casts a lot of doubt.

The docs do state that I can make up my own event names (for example, the doc page for .on() has an example to "Attach and trigger custom (non-browser) events"). But still, that's always attaching the event to a DOM element, not a plain old object.

Is there anything that definitively states whether jQuery supports .on() and .trigger() with plain old JavaScript objects?

like image 391
Joe White Avatar asked Nov 11 '11 22:11

Joe White


People also ask

Which jQuery method is used to attach an event handler function to an HTML element on mouse click?

The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element.

What does the event data object in jQuery help you do?

The event. data property is used to contain the optional data which is passed to an event method. The data passed when the currently executing handler is bound.

How do you call one event from another event in jQuery?

$('#b1'). on('click', function(){ $('#select_item'). trigger('change'); }); $('#select_item'). on('change', function(){ var jbyr = $(this).


1 Answers

Looking at the source code I found some hints that it's intended but then I also found this:

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.

http://forum.jquery.com/topic/triggering-custom-events-on-js-objects

like image 141
Esailija Avatar answered Sep 22 '22 17:09

Esailija