Clock Blog

Use jQuery Events on Plain JavaScript Objects

Posted on Wednesday, 25 July 2012 @ 00:00 GMT in tech-blogs by Ben Gourley

Did you know that you can use jQuery events on non-DOM-related objects? Just wrap up the object in the jQuery function, and you can use on, off and trigger.

// Create a plain object
var o = {}

// Bind an event handler
$(o).on('bump', function () {
  alert('ouch')
})

// Trigger an event
$(o).trigger('bump')

// Unbind event handlers
$(o).off('bump')

For some reason, this feature isn't documented, but it's really useful when you want an event listener mixin for your objects and you've already got jQuery on the page. It may not be the most performant event engine out there, but unless you've got hoards of events flying about, this solution is nice because you don't add any page bloat.

blog comments powered by Disqus