2013-02-27 71 views
0

我有一個用CoffeeScript編寫的非常簡單的程序,如果用戶點擊一個按鈕,應該在控制檯中顯示一個值。下面是我的代碼:值沒有被傳遞到類實例

HTML

<!DOCTYPE html> 
<html> 
<head> 

</head> 
<body> 
    <button id='butn'>click here</button> 

    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> 
    <script type="text/javascript" src="app.js"></script> 
</body> 
</html> 

app.js是編譯CoffeeScript的。我的CoffeeScript低於:

init.coffee

init = => 

    game = new Game() 


# Start it all off 
$(document).ready(init) 




game.coffee

class Game 

    constructor:() -> 

    @UI = new UI() 




ui.coffee

class UI 

    constructor:() -> 

    @toolbar = new Toolbar('foo') 



toolbar.coffee

class Toolbar 
    constructor: (@value) -> 

    @clickhandler() 


    clickhandler:() => 
    $('body').on 'click', '#butn', -> 
     console.log 'Value = ', @value 




編譯的JS是:

// Generated by CoffeeScript 1.3.3 
(function() { 
    var Game, Toolbar, UI, init, 
    _this = this, 
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; 

    init = function() { 
    var game; 
    return game = new Game(); 
    }; 

    $(document).ready(init); 

    Game = (function() { 

    function Game() { 
     this.UI = new UI(); 
    } 

    return Game; 

    })(); 

    UI = (function() { 

    function UI() { 
     this.toolbar = new Toolbar('foo'); 
    } 

    return UI; 

    })(); 

    Toolbar = (function() { 

    function Toolbar(value) { 
     this.value = value; 
     this.clickhandler = __bind(this.clickhandler, this); 

     this.clickhandler(); 
    } 

    Toolbar.prototype.clickhandler = function() { 
     return $('body').on('click', '#butn', function() { 
     return console.log('Value = ', this.value); 
     }); 
    }; 

    return Toolbar; 

    })(); 

}).call(this); 




的問題

值 '富' 不被顯示在控制檯上。控制檯記錄「Value =」但不是「foo」。請有人幫助我理解爲什麼以及如何在不改變我的程序的情況下解決此問題。

感謝您的幫助。

回答

2

您的問題是在事件處理程序中的this keyword的值,它指向DOM元素而不是工具欄實例。使用function binding

class Toolbar 
    constructor: (@value) -> 
    @clickhandler() 

    clickhandler:() -> 
    $('body').on 'click', '#butn', => 
     console.log 'Value = ', @value 
+0

謝謝你的幫助 – 2013-02-27 12:44:10