Skip to content

Instantly share code, notes, and snippets.

@wkronemeijer
Created November 2, 2013 17:22
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 wkronemeijer/7281274 to your computer and use it in GitHub Desktop.
Save wkronemeijer/7281274 to your computer and use it in GitHub Desktop.
custom EventTargets à la the DOM variant.
CustomEventTarget = (function () {
function CustomEventTarget() {
if (!(this instanceof CustomEventTarget)) {
return new CustomEventTarget();
};
Object.defineProperty(this, '_listeners_', {
value: {}
});
};
method(CustomEventTarget, 'addEventListener', function (type, func) {
this._listeners_[type] = this._listeners_[type] || [];
this._listeners_[type].push(func);
});
method(CustomEventTarget, 'removeEventListener', function (type, func) {
if (typeof this._listeners_[type] !== 'undefined') {
var index = this._listeners_[type].indexOf(func);
if (index !== -1) {
this._listeners_[type].splice(index, 1);
};
};
});
method(CustomEventTarget, 'dispatchEvent', function (type) {
if (typeof this._listeners_[type] !== 'undefined') {
var args = Array.prototype.slice.call(arguments).slice(1);
var self = this;
self._listeners_[type].forEach(function (elem) {
elem.apply(self, args);
});
};
});
return CustomEventTarget
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment