2013-03-10 62 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