Tiny JavaScript observer snippet
2013-09-26
Once in a while you stumble across those tiny snippets of code that ends up being a part of your project scaffolding.
I recently found one of these awesome snippets while browsing github for cool projects.
Its name is MicroEvent and is a tiny observer type event system for javascript.
It handles all your eventing for small projects and libraries, and fits in very few lines of code:
1var MicroEvent = function() {};
2MicroEvent.prototype = {
3 bind: function(event, fct) {
4 this._events = this._events || {};
5 this._events[event] = this._events[event] || [];
6 this._events[event].push(fct);
7 },
8 once: function (event, fct) {
9 var wrapper = function () {
10 this.unbind(event, wrapper);
11 fct.apply(this, Array.prototype.slice.call(arguments, 0));
12 };
13 this.bind(event, wrapper);
14 },
15 unbind: function(event, fct) {
16 this._events = this._events || {};
17 if (event in this._events === false) return;
18 this._events[event].splice(this._events[event].indexOf(fct), 1);
19 },
20 trigger: function(event /* , args... */ ) {
21 this._events = this._events || {};
22 if (event in this._events === false) return;
23 for (var i = 0; i < this._events[event].length; i++)
24 this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1));
25 }
26};
27MicroEvent.mixin = function(destObject) {
28 var props = ['bind', 'unbind', 'trigger', 'once'];
29 for (var i = 0; i < props.length; i++) {
30 if (typeof destObject === 'function') {
31 destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
32 } else {
33 destObject[props[i]] = MicroEvent.prototype[props[i]];
34 }
35 }
36};
I added the .once()
function since i use that a lot. I never had the need for an .unonce()
but that would also be fairly easy to implement.
And you add the MicroEvent mixins to your prototype with
I think this is one of those pieces of code that makes you feel all warm and fuzzy inside. :)