2013-03-10 33 views
1

我有一個簡單的類,盒:Coffeescript - 爲什麼我的類的屬性未定義onclick?

class Box 
    constructor: (@idx, grid) -> 
     console.log("constructing", @idx) 
     @elem = document.createElement("div") 
     @elem.id = "box" + idx 
     @elem.className = "box" 
     @elem.onclick = @toggle 
     grid.appendChild(@elem) 

    toggle:() -> 
     alert("click") 
     console.log("My idx is: ", @idx) 

當構造運行它報告「構建0」,「1建設」等,所以我知道正在定義的類屬性。如果我調用b.toggle()(其中b是一個box實例),那麼它會正確報告idx。但是,一旦我點擊頁面上的元素,它說@idx是未定義的。

所以看起來好像某種方式框的屬性丟失在事物的onclick方面。爲什麼是這樣?

以下是編譯的JavaScript:

Box = (function() { 

    function Box(idx, grid) { 
    this.idx = idx; 
    console.log("constructing", this.idx); 
    this.elem = document.createElement("div"); 
    this.elem.id = "box" + idx; 
    this.elem.className = "box"; 
    this.elem.onclick = this.toggle; 
    grid.appendChild(this.elem); 
    } 

    Box.prototype.toggle = function() { 
    alert("click"); 
    return console.log("My idx is: ", this.idx); 
    }; 

    return Box; 

})(); 

謝謝!

回答

4

使用fat arrowtoggle方法定義將其綁定到正確的上下文(在這種情況下,你的類的實例):

toggle: => 
    alert("click") 
    console.log("My idx is: ", @idx) 
+0

謝謝你,工作。 – dandelion 2013-03-10 23:34:39

4

nl_0有解決方案很好的答案。但是,在JavaScript的結尾,這就是爲什麼這不能很好地發揮作用。

Box函數它構造Box對象附加的toggle原型函數應用於所述元件與這行代碼:

this.elem.onclick = this.toggle; 

其結果,當功能toggle的內部,所有這些都是可訪問的是元件該事件附加到。因此,toggle裏面的thiselem,這就是爲什麼你看不到.idx就可以了。

+0

所以如果我有代碼this.this.toggle,它會工作? – dandelion 2013-03-10 23:50:38

+0

@danmane --HTMLElement沒有定義屬性this。爲了使''這個範圍與'Box'在這個意義上相同,那麼這個函數必須在構造函數中定義,並且'this'必須被緩存在一個通常名爲'self '。 – 2013-03-10 23:56:38

+0

我明白了,謝謝! (10char) – dandelion 2013-03-11 19:49:36

相關問題