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?
The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element.
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.
$('#b1'). on('click', function(){ $('#select_item'). trigger('change'); }); $('#select_item'). on('change', function(){ var jbyr = $(this).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With