Bind jQuery Events to Plain Objects

Sometimes you need a simple little pub-sub event model for your application. It’s fairly easy to write your own or include a small library, but if you’ve already got jQuery on the page, this might be good enough for you.

BindEventToPlainObject.js
1
2
3
4
5
6
7
var a = {};
$(a).on("myevent", function(e) {
console.log("myevent raised!");
});
$(a).trigger("myevent");

But watch out, this creates a new property on your object called something like jQuery19105992194800637662 that holds the event information. If you are iterating over the objects properties, you may not expect that to be yielded into your list.

Interestingly, this technique doesn’t quite work if the object is a function. The event instead gets bound onto the document, which is probably not what you want and could cause conflicts if you happen to reuse a real DOM event name.

But why would you want to bind an event to a function? If that function was a class constructor, maybe you wanted a “static” event for when anything happened in one of the instances.

BindEventToFunctionObject.js
1
2
3
4
5
6
7
8
9
10
11
12
var Dog = function(name) {
this.name = name;
$(Dog).trigger("created");
};
$(Dog).on("created", function(e) {
console.log("A dog was created!");
});
var fido = new Dog("Fido");
var roofus = new Dog("Roofus");

Be careful with this pattern, there are a couple of gotchas that may make it worth bringing in a full event implementation for all but the most basic of scripts.