scriptoj 看到的题目
下面是我的实现,暂时只能这样了,具体可看https://scriptoj.com/problems/36,方法很多
1、函数式编程(es6)
class EventEmitter {
constructor() {
this.events = {};
}
on(eventName, fn) {
let fnList = this.events[eventName] || [];
fnList.push(fn)
if (eventName) {
this.events[eventName] = fnList;
}
}
emit(eventName, ...agr) {
let funcs = this.events[eventName];
if (funcs && funcs.length) {
for (let j = 0; j < funcs.length; j++) {
funcs[j](...agr);
}
}
}
off(eventName, fn) {
let funcs = this.events[eventName];
if (fn) {
this.events[eventName].splice(fn, 1);
} else {
delete this.events[eventName]
}
}
}
2、es5 模拟vue事件
var App = {
eventList: [],
$on: function(event, cb) {
if (!event) return
this.eventList[event] = cb;
},
$emit: function(event, cb) {
if (!event) return
this.eventList[event]();
},
$off: function(event, cb) {
if (event) {
delete this.eventList[event]
} else {
this.eventList = [];
}
}
}