Created
July 22, 2011 12:23
-
-
Save katspaugh/1099345 to your computer and use it in GitHub Desktop.
Minimal observer, needed too often.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Observer = (function () { | |
'use strict'; | |
return { | |
on: function (event, fn) { | |
if (!this.handlers) { this.handlers = {}; } | |
var handlers = this.handlers[event]; | |
if (!handlers) { | |
handlers = this.handlers[event] = []; | |
} | |
handlers.push(fn); | |
}, | |
un: function (event, fn) { | |
if (!this.handlers) { return; } | |
var handlers = this.handlers[event]; | |
if (handlers && handlers.length) { | |
if (fn) { | |
var index = handlers.indexOf(fn); | |
if (index >= 0) { | |
handlers.splice(index, 1); | |
} | |
} else { | |
handlers.length = 0; | |
} | |
} | |
}, | |
fireEvent: function (event, data) { | |
if (!this.handlers) { this.handlers = {}; } | |
var handlers = this.handlers[event]; | |
if (handlers) { | |
var len = handlers.length; | |
for (var i = 0; i < len; i += 1) { | |
handlers[i](data); | |
} | |
} | |
} | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment