Skip to content

Instantly share code, notes, and snippets.

@fabioyamate
Created December 19, 2014 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabioyamate/5b318b272c8b7e7759ca to your computer and use it in GitHub Desktop.
Save fabioyamate/5b318b272c8b7e7759ca to your computer and use it in GitHub Desktop.
EventTarget mixin module
// draft
(function(exports) {
var ArrayProto = Array.prototype;
var nativeSlice = ArrayProto.slice,
nativeFilter = ArrayProto.filter;
/* Internal: filters the collection. (extracted from underscore.js)
*
* Returns the filtered list, given a function condition.
*/
function filter(obj, iterator, context) {
var results = [];
if (obj === null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
for (var i = 0, l = obj.length; i < l; ++i) {
if (iterator.call(context, obj[i], i)) results.push(obj[i]);
}
return results;
}
function EventTarget() {}
var fn = EventTarget.prototype;
fn.contructor = EventTarget;
fn.on(type, fn, context) {
if (!this.hasOwnProperty('_listeners')) {
this._listeners = {};
}
if (!this._listeners.hasOwnProperty(type)) {
this._listeners[type] = [];
}
this._listeners[type].push({ fn: fn, context: context || null });
};
fn.trigger = function(type) {
if (this._listeners && this._listener[type] instanceof Array) {
var args = nativeSlice.call(arguments, 1),
listeners = this._listeners[type];
for (var i = 0, len = listeners.length; i < len; i++) {
listeners[i].fn.apply(listeners[i].context, args);
}
}
};
fn.off = function(type, fn) {
if (this._listeners && this._listeners[type] instanceof Array) {
var listeners = this._listeners[type];
this._listeners[type] = filter(this._listeners[type], function(subscription) {
return subscription.fn !== fn;
});
}
};
exports.EventTarget = EventTarget;
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment