事件处理程序几乎只是在适当时间调用时运行的函数。听起来您希望另一个对象(即:按钮)响应事件,然后关闭您的对象。在这种情况下,按钮是事件侦听器,而不是您的对象,因此您可能只需将按钮的 onclick 处理程序设置为对象实例上的适当关闭函数。
如果你真的想反其道而行之,你可以做一些非常简单的事情,像这样:
var MyObj = function(h,w){
this.height = h;
this.width = w;
this.close = function(){ /** Do close */ }
this.addCloser = function(closebutton){ closebutton.onclick = this.close(); }
}
会这样使用:
var myo = new MyObj();
myo.addCloser(document.getElementById('mybutton'));
但是,如果您希望您的对象在应用注册的处理函数时生成事件,您可能需要做一些更复杂的事情,如下所示:
var MyObj = function(h,w){
this.height = h;
this.width = w;
this.handlers = {};
this.events = ['close', 'beforeclose'];
this.beforeClose = function(){
for(var i = 0, l = this.handlers.beforeclose.length; i < l; i++){
this.handlers.beforeclose[i].call(this);
}
}
this.afterClose = function(){
for(var i = 0, l = this.handlers.close.length; i < l; i++){
this.handlers.close[i].call(this);
}
}
this.close = function(){ this.beforeClose(); /**Do close */ this.afterClose(); }
this.registerHandler = function(type, func){
if(this.events.indexOf(type) == -1) throw "Invalid Event!";
if(this.handlers[type]){
this.handlers[type].push(func);
} else {
this.handlers[type] = [func];
}
}
}
或者其他,可以这样使用:
var myo = new MyObj();
myo.registerHandler('beforeclose', function(){alert("I'm closing!");});