admin管理员组文章数量:1427798
I have a view model something like this:
CANVAS = getElementById...
RemixView = function(attrs) {
this.model = attrs.model;
this.dragging = false;
this.init();
};
RemixView.prototype = {
init: function() {
CANVAS.addEventListener("click", this.handleClick);
},
handleClick: function(ev) {
var obj = this.getHoveredObject(ev);
},
getHoveredObject: function(ev) {}
...
...
}
rv = new RemixView()
the problem is my when clickHandler event fired, this object is being equal to CANVAS object, not RemixView. So I get an error that says:
this.getHoveredObject is not a function
What is correct approach at that stuation?
I have a view model something like this:
CANVAS = getElementById...
RemixView = function(attrs) {
this.model = attrs.model;
this.dragging = false;
this.init();
};
RemixView.prototype = {
init: function() {
CANVAS.addEventListener("click", this.handleClick);
},
handleClick: function(ev) {
var obj = this.getHoveredObject(ev);
},
getHoveredObject: function(ev) {}
...
...
}
rv = new RemixView()
the problem is my when clickHandler event fired, this object is being equal to CANVAS object, not RemixView. So I get an error that says:
this.getHoveredObject is not a function
What is correct approach at that stuation?
Share Improve this question edited Feb 9, 2021 at 17:28 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 16, 2012 at 20:58 Mirat Can BayrakMirat Can Bayrak 6517 silver badges19 bronze badges 03 Answers
Reset to default 4The usual approach is to use a simple closure for the callback and capture the appropriate value of this
in a local variable that the closure can reference:
RemixView.prototype = {
init: function(this) {
var _this = this;
CANVAS.addEventListener("click", function(ev) {
return _this.handleClick(ev);
});
},
//...
};
You could also use Function.prototype.bind
to make a bound function (as user123444555621 does):
RemixView.prototype = {
init: function(this) {
CANVAS.addEventListener("click", this.handleClick.bind(this));
},
//...
};
Or, if you want to use ES6, you could use an arrow function:
RemixView.prototype = {
init: function(this) {
CANVAS.addEventListener("click", ev => this.handleClick(ev));
},
//...
};
You want to bind the handler function:
CANVAS.addEventListener("click", this.handleClick.bind(this));
Note that this may not work in older browsers, but there are polyfills for those.
Make prototype
a function.
RemixView.prototype = function () {
init: function() {
CANVAS.addEventListener("click", this.handleClick);
},
handleClick: function(ev) {
var obj = this.getHoveredObject(ev);
} ///...
//...
}
本文标签: javascriptCalling function from an object with event listenerStack Overflow
版权声明:本文标题:javascript - Calling function from an object with event listener - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745508179a2661343.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论