Skip to content

Instantly share code, notes, and snippets.

@giscafer
Created May 23, 2018 07:20
Show Gist options
  • Save giscafer/2e76e561a9830d59a11784e531508550 to your computer and use it in GitHub Desktop.
Save giscafer/2e76e561a9830d59a11784e531508550 to your computer and use it in GitHub Desktop.
EventEmitter 事件式编程
"use strict"
/**事件式编程 */
class EventEmiter {
constructor(debug) {
this._debuger_ = !!debug;
this._callback_ = {};
this.commonApi();
}
debug(info) {
if (!this._debuger_) return;
console.log(info);
}
/**
* 事件监听
* @param {string} ev 事件名称
* @param {function} callback 回调函数
*/
addListener(ev, callback) {
this.debug(`Add listener for ${ev}`);
this._callback_[ev] = this._callback_[ev] || [];
this._callback_[ev].push(callback);
return this;
}
/**
* 移除事件监听
* @param {string} ev 事件名称
* @param {function} callback 回调函数
*/
removeListener(ev, callback) {
let calls = this._callback_;
if (!ev) {
this.debug('Remove all listeners');
this._callback_ = {};
return this;
}
if (!callback) {
this.debug(`Remove all listeners of ${ev}`);
calls[ev] = [];
return this;
}
let list = calls[ev] || [];
list.forEach((cb, index) => {
if (cb === callback) {
this.debug(`Remove all listeners of ${ev}`);
list[index] = null;
}
});
return this;
}
/**移除所有事件监听 */
removeAllListeners(eventName) {
this.removeListener(eventName);
}
/**
* 事件触发器
* @param {string} ev 事件名称
* @param {*} data 数据
*/
trigger(ev, data) {
let list, callback, calls = this._callback_;
if (!ev) return this;
list = calls[ev] || [];
list.forEach((cb, i) => {
if (!(callback = cb)) {
list.splice(i, 1);
} else {
let args = [];
for (let j = 1; j <= arguments.length; j++) {
args.push(arguments[j]);
}
callback.apply(this, args);
}
});
return this;
}
/**
* 兼容使用习惯
*/
commonApi() {
this.fire = this.trigger;
this.emit = this.trigger;
this.bind = this.addListener;
this.on = this.addListener;
this.unon = this.removeListener;
this.unbind = this.removeListener;
this.unbindAll = this.removeAllListeners;
}
}
module.exports = EventEmiter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment