Skip to content

Instantly share code, notes, and snippets.

@pwFoo
Forked from jhthorsen/dom-events.js
Created January 8, 2022 21:06
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 pwFoo/69098553b9fef441e09df280006924aa to your computer and use it in GitHub Desktop.
Save pwFoo/69098553b9fef441e09df280006924aa to your computer and use it in GitHub Desktop.
emit, on, once in pure javascript
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;
};
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