如何在 JavaScript 中将事件处理程序添加到对象的原型中

How to add eventhandlers to prototype of an object in JavaScript

本文关键字:添加 对象 原型 程序 事件处理 JavaScript      更新时间:2023-09-26
var MyObj = function(h,w){
   this.height = h;
   this.width  = w;
}

我想为此对象的所有实例注册一些事件处理程序。

例如,假设我想要一个关闭按钮,当用户单击该按钮时,它应该关闭该特定对象。

那么如何将事件处理程序添加到其原型中,以便我可以动态创建这些对象呢?

事件处理程序几乎只是在适当时间调用时运行的函数。听起来您希望另一个对象(即:按钮(响应事件,然后关闭您的对象。在这种情况下,按钮是事件侦听器,而不是您的对象,因此您可能只是将按钮的 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!");});