1

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?

0

3 Answers 3

4

The 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));
    },
    //...
};
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

problem is not about binding event, calling getHoveredObject method from handleClick method.
My answer is not about binding event.
0

Make prototype a function.

RemixView.prototype = function () {
    init: function() {
        CANVAS.addEventListener("click", this.handleClick);
    },
    handleClick: function(ev) {
        var obj = this.getHoveredObject(ev);
    } ///...
//...
}

1 Comment

here you're defining prototype as function but behaving it like object. i think init: must be this.init = function() { ... } ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.