title: 自定义事件
date: 2017-06-06 15:36:04
tags: 自定义事件
js的自定义事件
code
function EventTarget() {
this.handlers = {};
}
EventTarget.prototype = {
constructor: EventTarget,
addHandler: function(type, handler) {
if (typeof this.handlers[type] == 'undefined') {
this.handlers[type] = [];
}
this.handlers[type].push(handler);
},
fire: function(type, event) {
if (!event.target) {
event.target = this;
}
if (this.handlers[type] instanceof Array) {
var handlers = this.handlers[type];
for (var i = 0, len = handlers.length; i < len; i++) {
handlers[i](event);
}
}
},
remove: function(type, handler) {
if (this.handlers[type] instanceof Array) {
var handlers = this.handlers[type];
for (var i = 0, len = handlers.length; i < len; i++) {
if (handlers[i] === handler) {
break;
}
}
handlers.splice(i, 1);
}
}
};
usage
var target = new EventTarget();
//事件处理函数
function fn(event){
console.log(event);
}
//注册事件
target.addHandler('testEvent', fn);
//触发事件
target.fire('testEvent', {name : 'Cloud'});//第二个参数是传递的内容,可自定义
用处
- 可以用于界面间的传值
- 创建松耦合的代码