JavaScript中是否有最佳实践或常用方法将类成员作为事件处理程序?
考虑以下简单示例:
事件处理程序buttonClicked被调用,但_clickCount成员不可访问,或这指出了一些其他对象.
关于这类问题的任何好的提示/文章/资源?
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
直接附加到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'))
我不知道为什么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'); } }