"use strict";
var coreEvent = /** @class */ (function () {
function coreEvent() {
this.handlers = {};
}
// 訂閱/註冊事件
coreEvent.prototype.on = function (eventType, handler) {
// 添加事件
if (!(handler in this.handlers)) {
this.handlers[eventType] = [];
}
this.handlers[eventType].push(handler);
return this;
};
// 發佈事件
coreEvent.prototype.emit = function (eventType) {
var handlerArgs = Array.prototype.slice.call(arguments, 1);
if (this.handlers[eventType]) {
for (var i = this.handlers[eventType].length - 1; i >= 0; i--) {
this.handlers[eventType][i].apply(this, handlerArgs);
}
}
return this;
};
// 刪除事件
coreEvent.prototype.remove = function (eventType) {
var currentHandler = this.handlers[eventType];
if (currentHandler) {
var len = currentHandler.length;
currentHandler.splice(0, len);
}
return this;
};
return coreEvent;
}());app
var event = new coreEvent();
測試用例測試
let i = 0;
setInterval(() => {
var str = '價格是' + i++
var str1 = '價格是' + i++
event.emit('price', str)
event.emit('price1', str1)
}, 1000)
event.on('price', function(data) {
console.log('訂閱事件price', data)
})
event.on('price', function(data) {
console.log('訂閱事件price', data)
})
event.on('price1', function(data) {
console.log('訂閱事件price1', data)
})
setTimeout(()=>{
event.remove('price')
},3000)this