js事件模型與自定義事件實例解析
JavaScript 一個最簡單的事件模型,需要有事件綁定與觸發(fā),還有事件刪除。
var eventModel = {
list: {},
bind: function () {
var args = [].slice.call(arguments),
type = args[0],
handlers = args.slice(1);
if (typeof type === 'string' && handlers.length > 0) {
for (var i = 0; i < handlers.length; i++) {
if (typeof handlers[i] === 'function') {
if (!this.list[type]) {
this.list[type] = [];
}
this.list[type].push(handlers[i]);
}
}
}
},
unbind: function () {
var type = arguments[0],
handlers = Array.prototype.slice.call(arguments, 1);
if (typeof type === 'string') {
if (handlers.length === 0) {
this.list[type] = [];
} else {
for (var i = 0; i < handlers.length; i++) {
if (typeof handlers[i] === 'function' && handlers[i] === this.list[type][i]) {
this.list[type].splice(i, 1);
}
}
}
}
},
trigger: function () {
var arguments = [].slice.call(arguments),
type = arguments[0],
args = arguments[1] instanceof Array && !arguments[2] ? arguments[1] : arguments.slice(1),
handlers = this.list[type];
for (var i = 0; i < handlers.length; i++) {
handlers[i].apply(this, args.splice(0, handlers[i].length));
}
}
};
其中主要實現(xiàn)了bind(綁定事件)、unbind(刪除事件)與 trigger (觸發(fā)事件)。對同一事件名稱,可以綁定多個事件處理函數(shù);并按照綁定的順序依次觸發(fā)。
args.splice(0, handlers[i].length) 觸發(fā)時的傳參
事件綁定與觸發(fā):
eventModel.bind('myevent1', function (a) {
console.log(a); // 1
}, function(b) {
console.log(b); // 2
}, function(c, d) {
console.log(c + ' + ' + d); // a + b
});
eventModel.bind('myevent1', function (e) {
console.log(e); // 50
});
eventModel.trigger('myevent1', 1,2,'a','b', 50);
事件刪除:
<button id="bind">bind</button> <button id="unbind">unbind</button>
var fnX = function () {
console.log('fnX');
}
var fnY = function () {
console.log('fnY');
}
eventModel.bind('myevent2', fnX, fnY);
document.getElementById('unbind').onclick = function () {
eventModel.unbind('myevent2', fnX); //刪除 fnX 后,只剩下 fnY
};
document.getElementById('bind').onclick = function () {
eventModel.trigger('myevent2'); //輸出 fnX fnY
//在點擊unbind后,只輸出 fnY
};
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
C#寫入對象或集合類型數(shù)據(jù)到xml文件的方法
這篇文章主要介紹了C#寫入對象或集合類型數(shù)據(jù)到xml文件的方法,涉及C#針對XML文件的相關(guān)操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07
DevExpress實現(xiàn)TreeList父子節(jié)點CheckState狀態(tài)同步的方法
這篇文章主要介紹了DevExpress實現(xiàn)TreeList父子節(jié)點CheckState狀態(tài)同步的方法,需要的朋友可以參考下2014-08-08
C#數(shù)據(jù)表格(DataGridView)控件的應(yīng)用案例
這篇文章主要介紹了C#數(shù)據(jù)表格(DataGridView)控件的應(yīng)用案例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03

