额,参考了几种方法,特做以下实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<html>
<body>
 
</body>
</html>
<script>
 
function $extend(object,src){
	if(!src)return object;
	for (var p in src){
		object[p] = src[p];
	}
	return object;
}
 
 
var $A = function(o){
  	var rt = [];
	for (var i = 0,j = o.length;i < j;i++){
		rt.push(o[i]);
	}
	return rt;
}
 
 
function enableCoustomEvent(obj){
	$extend(obj,{
		addEvent:function(type,func){
			if(!this._customEventListeners)this._customEventListeners = {};
			var funcs = this._customEventListeners;
			funcs[type] ? funcs[type].push(func) : funcs[type] = [func];			
		},
		delEvent:function(type,func){
			var funcs = this._customEventListeners[type];
			if(funcs){
				for(var i = funcs.length - 1; i >= 0;i--){
					if(funcs[i] == func){
						funcs[i] = null;
						break;
					}
				}
			}
		},
		fireEvent:function(type){
			if(!this._customEventListeners[type])return;
			var funcs = this._customEventListeners[type],s = this,ars = $A(arguments);
			ars.shift();
			for(var i = funcs.length - 1; i >= 0; i--){
				if(funcs[i])
					funcs[i].apply(s,ars);
			}
		}
	});
}
 
function echo(s){
	alert(s);
}
 
function log(s){
	document.body.appendChild(document.createTextNode(s));
}
 
function myobj(){
 
}
 
myobj.prototype = {
	run:function(){
		this.fireEvent('haha','动感超人');
	},
	fireEvent:function(){}
};
 
enableCoustomEvent(myobj.prototype);
 
var o = new myobj();
o.addEvent('haha',echo);
o.addEvent('haha',log);
o.run();
o.delEvent('haha',echo);	
o.run();
</script>
Copy Code | Run Code