1

我有一个像这样的视图模型:

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()

问题是我在触发 clickHandler 事件时,该对象等于CANVAS对象,而不是 RemixView。所以我收到一条错误消息:

this.getHoveredObject 不是函数

在那种情况下正确的方法是什么?

4

3 回答 3

4

通常的方法是对回调使用简单的闭包,并this在闭包可以引用的局部变量中捕获适当的值:

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

您还可以Function.prototype.bind用来制作绑定函数(如user123444555621所做的那样):

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

或者,如果你想使用 ES6,你可以使用箭头函数

RemixView.prototype = {
    init: function(this) {
        CANVAS.addEventListener("click", ev => this.handleClick(ev));
    },
    //...
};
于 2012-06-16T21:08:53.733 回答
1

你想绑定处理函数:

CANVAS.addEventListener("click", this.handleClick.bind(this));

请注意,这可能不适用于旧版浏览器,但有针对这些的polyfills

于 2012-06-16T21:18:16.440 回答
0

prototype一个函数。

RemixView.prototype = function () {
    init: function() {
        CANVAS.addEventListener("click", this.handleClick);
    },
    handleClick: function(ev) {
        var obj = this.getHoveredObject(ev);
    } ///...
//...
}
于 2012-06-16T21:21:27.883 回答