当前位置:  开发笔记 > 编程语言 > 正文

类方法作为JavaScript中的事件处理程序?

如何解决《类方法作为JavaScript中的事件处理程序?》经验,为你挑选了3个好方法。

JavaScript中是否有最佳实践或常用方法将类成员作为事件处理程序?

考虑以下简单示例:


    


    
    

事件处理程序buttonClicked被调用,但_clickCount成员不可访问,或指出了一些其他对象.

关于这类问题的任何好的提示/文章/资源?



1> pawel..:
ClickCounter = function(buttonId) {
    this._clickCount = 0;
    var that = this;
    document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };
}

ClickCounter.prototype = {
    buttonClicked: function() {
        this._clickCount++;
        alert('the button was clicked ' + this._clickCount + ' times');
    }
}

编辑差不多10年后,使用ES6,箭头功能和类属性

class ClickCounter  {
   count = 0;
   constructor( buttonId ){
      document.getElementById(buttonId)
          .addEventListener( "click", this.buttonClicked );
  }
   buttonClicked = e => {
     this.count += 1;
     console.log(`clicked ${this.count} times`);
   }
}

https://codepen.io/anon/pen/zaYvqq


这是一个很好的例子,但是这个答案可能会更好一些解释为什么它是一个很好的解决方案,对于这里的新手.

2> AnthonyWJone..:

直接附加到onclick属性的函数将具有this指向元素的执行上下文属性.

当你需要一个元素事件来对象的特定实例(在.NET中作为委托)运行时,你需要一个闭包: -

function MyClass() {this.count = 0;}
MyClass.prototype.onclickHandler = function(target)
{
   // use target when you need values from the object that had the handler attached
   this.count++;
}
MyClass.prototype.attachOnclick = function(elem)
{
    var self = this;
    elem.onclick = function() {self.onclickHandler(this); }
    elem = null; //prevents memleak
}

var o = new MyClass();
o.attachOnclick(document.getElementById('divThing'))



3> kucherenkovo..:

我不知道为什么Function.prototype.bind这里没有提到。所以我就把这个留在这里;)

ClickCounter = function(buttonId) {
    this._clickCount = 0;
    document.getElementById(buttonId).onclick = this.buttonClicked.bind(this);
}

ClickCounter.prototype = {
    buttonClicked: function() {
        this._clickCount++;
        alert('the button was clicked ' + this._clickCount + ' times');
    }
}

推荐阅读
mylvfamily
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有