【问题标题】:How to add eventhandlers to prototype of an object in JavaScript如何将事件处理程序添加到 JavaScript 中的对象原型
【发布时间】:2012-02-04 00:47:38
【问题描述】:
var MyObj = function(h,w){
   this.height = h;
   this.width  = w;
}

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

比如说我想要一个关闭按钮,当用户点击按钮时,它应该关闭那个特定的对象。

那么如何将事件处理程序添加到它的原型中,以便我可以即时创建这些对象?

【问题讨论】:

  • close that specific Object 是什么意思?这样的对象有什么作用?您必须提供更多信息。事件处理程序只是函数。
  • 可以有多个对象实例,当我关闭一个对象时,该对象应该关闭而不是其他对象。

标签: javascript dom-events unobtrusive-javascript


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 2014-01-13
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多