定義: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');
複製代碼