-
-
Save pwFoo/69098553b9fef441e09df280006924aa to your computer and use it in GitHub Desktop.
emit, on, once in pure javascript
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
Object.prototype.emit = function(name, d) { | |
this.dispatchEvent(new CustomEvent(name, { detail: d })); | |
return this; | |
}; | |
Object.prototype.on = function(name, cb) { | |
this.addEventListener(name, cb, false); | |
return cb; | |
}; | |
Object.prototype.once = function(name, cb) { | |
var wrapper = function() { | |
this.removeEventListener(name, wrapper, false); cb.apply(this, arguments); | |
}; | |
this.addEventListener(name, wrapper, false); | |
return wrapper; | |
}; |
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
Object.prototype.$emit = function(name) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
if (this._events && this._events[name]) | |
this._events[name].forEach(function(cb) { cb.apply(this, args) }.bind(this)); | |
return this; | |
}; | |
Object.prototype.$off = function(name, cb) { | |
if (!this._events) return this; | |
if (!cb) delete this._events[name]; | |
if (this._events[name]) this._events[name] = this._events[name].filter(function(i) { return i != cb }); | |
return this; | |
}; | |
Object.prototype.$on = function(name, cb) { | |
if (!this._events) this._events = {}; | |
if (!this._events[name]) this._events[name] = []; | |
this._events[name].push(cb); | |
return cb; | |
}; | |
Object.prototype.$once = function(name, cb) { | |
var wrapper, self = this; | |
wrapper = function() { self.$off(name, wrapper); cb.apply(this, arguments); }; | |
this.$on(name, wrapper); | |
return wrapper; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment