定义:app
事件机制自己就是一种观察者模式函数
观察者的使用场景就是:学习
实现一个Event模块this
源码实现spa
// Event事件模块
function Event() {
// 存储不一样的事件类型对应不一样的处理函数 保证后续emmit能够执行
this.cache = [];
}
// 绑定自定义事件模块
Event.prototype.on = function(type, handle) {
if(!this.cache[type]) {
this.cache[type] = [handle];
}else {
this.cache[type].push(handle);
}
}
// 自动触发事件的功能
Event.prototype.emmit = function() {
// 没有保证参数是多少个 就用arguments
// 事件类型
var type = arguments[0];
// 绑定函数
var arg = [].slice.call(arguments, 1);
for(var i = 0; i < this.cache[type].length; i++) {
this.cache[type][i].apply(this, arg);
// 检查是否有标记
if(this.cache[type][i].flag) {
this.cache[type].splice(i, 1);
}
}
}
// 所有清除绑定
Event.prototype.empty = function(type) {
this.cache[type] = [];
}
// 清除自定义事件的功能
Event.prototype.remove = function(type, handle) {
this.cache[type] = this.cache[type].filter(function(ele) {
return ele != handle;
})
}
// 只触发一次事件的功能
Event.prototype.once = function(type, handle) {
if(!this.cache[type]) {
this.cache[type] = [];
}
// 作标记
handle.tag = 'true';
this.cache[type].push(handle);
}
var oE = new Event();
function deal1(time) {
console.log('overtime1:' + time);
}
oE.on('over', deal1);
function deal2(time) {
console.log('overtime2:' + time);
}
oE.on('over', deal2);
oE.emmit('over', '2018-9-25');
oE.remove('over', deal2);
oE.emmit('over', 'second-1-1');
复制代码