Lan*_*box 1 javascript prototype addeventlistener
我在这里遇到一个小问题,我不想向单击事件添加事件侦听器。当点击发生时,函数会正常触发,但是当它应该调用另一个函数时,它会给出错误:
TypeError: this.addEvent is not a function
Run Code Online (Sandbox Code Playgroud)
代码:
class TEST {
construct(){
this.events = [];
}
}
TEST.prototype.ready = function(callback) {
if (document.readyState!='loading') callback();
else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
else document.attachEvent('onreadystatechange', function(){
if (document.readyState=='complete') callback();
});
}
TEST.prototype.addEvent = function (event) {
this.events.push(event);
}
TEST.prototype.clickEvent = function (e) {
var pos = {
x: e.pageX,
y: e.pageY
};
var event = {
type: 'click',
data: pos,
timestamp: new Date()
};
this.addEvent(event);
}
TEST.prototype.init = function () {
document.addEventListener('click', this.clickEvent);
}
var test = new TEST();
test.ready(function(){
test.init();
});
Run Code Online (Sandbox Code Playgroud)
JSFiddle: https:
//jsfiddle.net/x2hLw009/
任何帮助表示赞赏,谢谢!
编辑
我添加了绑定到 addEventListener:
document.addEventListener('click', this.clickEvent.bind(this));
Run Code Online (Sandbox Code Playgroud)
但是当函数继续到 this.addEvent() 时,我收到新错误:
TypeError: this.events is undefined
Run Code Online (Sandbox Code Playgroud)
在这一行:
this.events.push(event);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1391 次 |
| 最近记录: |