js 實現釋出訂閱模式
/* Pubsub */
function Pubsub(){
//存放事件和對應的處理方法
this.handles = {};
}
Pubsub.prototype = {
//傳入事件型別type和事件處理handle
on: function (type, handle) {
if(!this.handles[type]){
this.handles[type] = [];
}
this.handles[type].push(handle);
},
emit: function () {
//通過傳入引數獲取事件型別
//將arguments轉為真陣列
var type = Array.prototype.shift.call(arguments);
if(!this.handles[type]){
return false;
}
for (var i = 0; i < this.handles[type].length; i++) {
var handle = this.handles[type][i];
//執行事件
handle.apply(this, arguments);
}
},
off: function (type, handle) {
handles = this.handles[type];
if(handles){
if(!handle){
handles.length = 0;//清空陣列
}else{
for (var i = 0; i < handles.length; i++) {
var _handle = handles[i];
if(_handle === handle){
//從陣列中刪除
handles.splice(i,1);
}
}
}
}
}
let p1 = new Pubsub();
p1.on('detail', (name)=> {console.log(name)});
p1.emit('detail', 'observer')
let p2 = new Pubsub();
p2.on('detail', (name)=> {console.log(name)});
p2.emit('detail', 'observer2')
p2.off('detail');
p2.emit('detail', 'observer3');
轉自 https://segmentfault.com/a/1190000012430769