2012-06-16 45 views
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 is not a function 

什麼是正確的方法在那stutry?

回答

2

通常的方法是使用一個簡單的關閉回調和捕捉this適當的值在一個局部變量,封閉可以參考:

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

它的工作表示感謝! –

0

你想bind處理函數:

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

請注意,這可能不適用於較舊的瀏覽器,但有polyfills這些。

+0

問題不是綁定事件,而是從** handleClick **方法調用** getHoveredObject **方法。 –

+0

我的回答不是約束事件。 – user123444555621

0

使prototype功能。

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

在這裏,您將原型定義爲函數,但其​​行爲與對象相同。我認爲init:必須是this.init = function(){...}? –

相關問題