很多人听到事件,就会想到addEventListener,但在这个题目里,并不需要,而且addEventListener是针对dom的事件绑定,我们需要的是任何时候的自定义事件。
function Event() {
this._events = {};
}
Event.prototype.on = function(type, fn) {
if (!this._events[type]) {
this._events[type] = []
}
this._events[type].push(fn);
}
Event.prototype.off = function(type, fn) {
if (!this._events[type]) {
return;
}
if (!fn) {
this._events[type] = undefined;
return;
}
var index = this._events[type].indexOf(fn);
this._events[type].splice(index, 1);
}
Event.prototype.emit = function(type) {
if (!this._events[type]) {
return;
}
this._events[type].forEach(fn => fn());
}
Event.prototype.once = function(type, fn) {
var _ = this;
var _fn = () => {
fn.apply(_, arguments);
this.off(type);
};
this.on(type, _fn);
}
如果需要更复杂的定义,可以参考VUE的源码: github.com/vuejs/vue/b…