JS-觀察者模式-初摸
阿新 • • 發佈:2018-11-20
var Event = {
// 通過on介面監聽事件eventName
// 如果事件eventName被觸發,則執行callback回撥函式
on: function (eventName, callback) {
if (!this.handles) {
this.handles = {};
Object.defineProperty(this, "handles", {
//限制下方Object.assign淺拷貝列舉物件
value: {},
enumerable: false,
configurable: true,
writable: true
})
}
if (!this.handles[eventName]) {
this.handles[eventName] = [];
}
this.handles[eventName].push(callback);
},
// 觸發事件 eventName
emit: function (eventName) {
//你的程式碼
if (this.handles[arguments[0]]) {
for (var i = 0; i < this.handles[arguments[0]].length; i++) {
this.handles[arguments[0]][i](arguments[1]);
}
}
}
};
Event.on('test', function (result) {
console.log(result);
});
Event.on('test', function () { console.log('test'); }); // Event.emit('test', 'hello world'); // 輸出 'hello world' 和 'test' var person1 = {}; var person2 = {}; Object.assign(person1, Event); Object.assign(person2, Event); person1.on('call1', function () { console.log('person1'); }); person2.on('call2', function () { console.log('person2'); }); person1.emit('call1'); // 輸出 'person1' person1.emit('call2'); // 沒有輸出 無該屬性 person2.emit('call1'); // 沒有輸出 無該屬性 person2.emit('call2'); // 輸出 'person2'
Event.on('test', function () { console.log('test'); }); // Event.emit('test', 'hello world'); // 輸出 'hello world' 和 'test' var person1 = {}; var person2 = {}; Object.assign(person1, Event); Object.assign(person2, Event); person1.on('call1', function () { console.log('person1'); }); person2.on('call2', function () { console.log('person2'); }); person1.emit('call1'); // 輸出 'person1' person1.emit('call2'); // 沒有輸出 無該屬性 person2.emit('call1'); // 沒有輸出 無該屬性 person2.emit('call2'); // 輸出 'person2'