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

时间:2008-10-23 09:21:47

标签: javascript html function class

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

考虑以下简单示例:

<head>
    <script language="javascript" type="text/javascript">

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

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

    </script>
</head>
<body>
    <input type="button" id="btn1" value="Click me" />
    <script language="javascript" type="text/javascript">
        var btn1counter = new ClickCounter('btn1');
    </script>
</body>

调用事件处理程序buttonClicked,但_clickCount成员无法访问,或指向其他对象。

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

5 个答案:

答案 0 :(得分:21)

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 properties

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

答案 1 :(得分:7)

直接附加到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'))

答案 2 :(得分:2)

我不知道为什么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');
    }
}

答案 3 :(得分:2)

您可以使用fat-arrow语法,该语法绑定到函数的词法范围

function doIt() {
  this.f = () => {
    console.log("f called ok");
    this.g();
  }
  this.g = () => {
    console.log("g called ok");
  }
}

之后你可以尝试

var n = new doIt();
setTimeout(n.f,1000);

您可以在babel上试用,或者如果您的浏览器支持jsFiddle上的ES6。

不幸的是,ES6 Class -syntax似乎不允许创建词法绑定到此的功能。我个人认为不妨这样做。编辑:似乎有experimental ES7 feature to allow it

答案 4 :(得分:0)

我喜欢使用 unnamed 函数,只是实现了一个可以正确处理此问题的导航类:

this.navToggle.addEventListener('click', () => this.toggleNav() );

那么 this.toggleNav() 可以只是 Class 中的一个函数。

我知道我曾经调用一个命名函数,但它可以是你放在中间的任何代码,如下所示:

this.navToggle.addEventListener('click', () => { [any code] } );

因为 arrow 您传递了 this 实例并且可以在那里使用它。

Pawel 有一些不同的约定,但我认为使用 functions 更好,因为 ClassesMethods 的命名约定是要走的路:-)

相关问题