Adr*_*ire 0 javascript oop javascript-events
通常我在JavaScript中使用对象来保存数据,但事件侦听器不允许辅助指针来检索这些对象.
在事件回调中检索对象指针的最佳方法是什么?(请不要第三方图书馆)
例:
function MyClass()
{
this.number = Math.random();
this.button = document.createElement('div');
this.button.appendChild(document.createTextNode('Show number'));
document.body.appendChild(this.button);
// THIS FOLLOWING LINE REQUIRE CHANGES
this.button.addEventListener('click', MyClass.prototype.listener);
}
MyClass.prototype.listener = function (e)
{
// HERE, "THIS" DO NOT POINT TO MY OBJECT
alert( this.number );
}
testMyClass1 = new MyClass();
testMyClass2 = new MyClass();
Run Code Online (Sandbox Code Playgroud)
目前,我使用静态数组来保存指针,但这很难维护:
//New constructor, first try
function MyClass()
{
this.number = Math.random();
this.button = document.createElement('div');
this.button.appendChild(document.createTextNode('Show number'));
document.body.appendChild(this.button);
if (undefined===MyClass.prototype.register) MyClass.prototype.register = [];
this.id = MyClass.prototype.register.length;
MyClass.prototype.register.push(this);
this.callback = new Function( 'e',
'var self = MyClass.prototype.register[' + this.id + '];'+
'MyClass.prototype.listener.call(self, e);'
);
this.button.addEventListener('click', this.callback);
}
Run Code Online (Sandbox Code Playgroud)
笔记:
如果使用ES5:
this.button.addEventListener('click', MyClass.prototype.listener.bind(this));
Run Code Online (Sandbox Code Playgroud)
如果不使用ES5,得到一个垫片的Function.bind.
请注意,这确实会创建一个新的函数对象作为类的每个实例的处理程序,但是没有简单的方法可以避免这种情况.
| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |