自定义事件

/**
* 自定义事件
* 一般需要实现3个方法
* addEvent fire和remove
*/
function CustomEvent(){
	this._listeners = {};
}
CustomEvent.prototype = {
	constructor: CustomEvent,
	addEvent: function(type, listener){
		if(typeof this._listeners[type] == "undefined"){
			this._listeners[type] = [];
		}
		
		this._listeners[type].push(listener);
	},
	
	fire: function(event){
		if(typeof event == "string"){
			event = {type : event};
		}
		if(!event.target){
			event.target = this;
		}
		if(!event.type){
			throw new Error("Event object missting type property.");
		}
		if(this._listeners[event.type] instanceof Array){
			var listeners = this._listeners[event.type];
			for(var i = 0 , len = listeners.length ; i < len ; i++){
				listeners[i].call(this, event);
			}
		}
	},
	remove: function(type, listener){
		if(this._listeners[type] instanceof Array){
			var listeners = this._listeners[type];
			for(var i = 0 , len = listeners.length ; i < len ; i++){
				if(listeners[i] === listener){
					listeners.splice(i, 1);
					break;
				}
			}
		}
	}
	
}

 

你可能感兴趣的:(自定义)