title: js custom-event
date: 2018-09-08 20:41:49
tags:
类似于 jq的.on('click',fn) 的自定义事件
class Emitter {
constructor(_listeners) {
this._listeners = {};
}
subscribe(type,callback) {
if (typeof this._listeners[type] === "undefined") {
this._listeners[type] = [];
}
if (typeof callback === "function") {
this._listeners[type].push(callback);
}
return this;
}
emit(type) {
var args = Array.prototype.slice.call(arguments, 0)
var event = args.shift()
var list, events
if ( !(events = this._listeners) ) return
if ( !(list = this._listeners[event]) ) return
for (var i=0; i<list.length; i++) {
list[i].apply(this, args)
}
return this
}
release(type, fn) {
if (typeof type === "string") {
this._listeners[type].splice(fn, 1);
}
return this;
}
}
const emitter = new Emitter();
const array = [];
const sub1 = emitter.subscribe('click', (...args)=> console.log(args));
array.push({sub1:0})
const sub2 = emitter.subscribe('click', (...args)=> console.log(args));
array.push({sub1:1})
emitter.release('click', array.sub1)
emitter.emit('click',1,2)