JS的自定义事件

一个简单的自定义事件的方法:

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
// 定义类 class1
function class1() {
	// 构造函数
}
// 定义类成员
class1.prototype = {
	show : function() {
		// show 的代码
		// ...
		// 如果有事件绑定则循环onshow数组,触发该事件
		if (this.onshow) {
			for (var i = 0; i < this.onshow.length; i++) {
				this.onshow[i](); // 调用事件处理程序
			}
		}
	},
	attachOnShow : function(_eHandler) {
		if (!this.onshow)
			this.onshow = []; // 用数组存储绑定的事件处理程序引用
		this.onshow.push(_eHandler);
 
	}
}
var obj = new class1();
// 事件处理程序1
function onShow1() {
	alert(1);
}
// 事件处理程序2
function onShow2() {
	alert(2);
}
// 绑定两个事件处理程序
obj.attachOnShow(onShow1);
obj.attachOnShow(onShow2);
// 调用show,触发onshow事件
obj.show();

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">