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);
} ///...
//...
}