//将有参数的函数封装为无参数的函数
function createFunction(obj, strFunc) {
var args = []; //定义args 用于存储传递给事件处理程序的参数
if (!obj) obj = window; //如果是全局函数则obj=window;
//得到传递给事件处理程序的参数
for (var i = 2; i < arguments.length; i++) args.push(arguments[i]);
//用无参数函数封装事件处理程序的调用
return function() {
obj[strFunc].apply(obj, args); //将参数传递给指定的事件处理程序
}
}
function class1() {
}
class1.prototype = {
show: function() {
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);
},
detachOnShow: function(_eHandler) { // 移除事件
if (!this.onShow) { this.onShow = []; }
this.onShow.pop(_eHandler);
}
}
function objOnShow(userName) {
alert("hello," + userName);
}
function objOnShow2(testName) {
alert("show:" + testName);
}
function test() {
var obj = new class1();
var userName = "your name";
obj.attachOnShow(createFunction(null, "objOnShow", userName));
obj.attachOnShow(createFunction(null, "objOnShow2", "test message"));
obj.show();
obj.detachOnShow(createFunction(null, "objOnShow", userName));
obj.show(); // 移除一个,显示剩余的一个
obj.detachOnShow(createFunction(null, "objOnShow2", "test message"));
obj.show(); // 两个都移除,一个也不显示
}