2013-02-02 22 views
1

我試圖用骨幹與CoffeeScript的替代的javascript:的ReferenceError:的TodoItem沒有定義骨幹+ CoffeeScript的

TodoItem = Backbone.Model.extend(
    toggleStatus: -> 
    if @.get 'status' is "incomplete" 
     @.set 'status': 'complete' 
    else 
     @.set 'status': 'incomplete' 
    @.save() 
    ) 

todoItem = new TodoItem(
    description: 'I play the guitar' 
    status: 'incomplete' 
    id: 1 
) 

TodoView = Backbone.View.extend(
    tagName: 'div' 
    id: "box" 
    className: 'red-box' 

    events: 
    "click h3": "alertStatus" 
    'change input': 'toggleStatus' 

    template: 
    _.template "<h3> <input type=checkbox #{ print "checked" if status is "complete"} /> <%= description %></h3>" 

    initialize: -> 
    @.model.on 'change', @.render, @ 
    @.model.on 'destroy', @.remove, @ 

    toggleStatus: -> 
    @.model.toggleStatus() 

    alertStatus: -> 
    alert('Hey you clicked the h3!') 

    remove: -> 
    @.$el.remove() 

    render: -> 
    @.$el.html @.template(@.model.toJSON()) 
) 

todoView = new TodoView({model: todoItem}) 
todoView.render() 
console.log todoView.el 

如果我嘗試在控制檯:

todoItem.set({description: 'asdfadfasdfa'}); 

我得到:

ReferenceError: todoItem is not defined 

此外,我看不到我的身體裏面的div:

<div id="box" class="red-box"> 
    <h3> 
    <input type="checkbox" undefined> 
    "I play the guitar" 
    </h3> 
</div> 

但我可以在我的控制檯中看到這個div。

它在哪裏出錯?

謝謝!

+0

Afaik下劃線使得所有的變量都是本地的,所以你不能從控制檯訪問它們而沒有聲明它們是全局的。 – Bergi

+0

你究竟是什麼意思,「*我不能看到我的身體裏面的div *」? – Bergi

+0

謝謝,我的意思是''div id =「box」class =「red-box」> ...'不會在我的html頁面中呈現。你可以粘貼一個例子來解決這個問題嗎?謝謝! – hyperrjas

回答

1

CoffeeScript的好處之一是,您可以使用@foo而不是@.foo。少寫一點,好一點點閱讀。


您不必使用骨幹.extend(),因爲CoffeeScript中有一個完全兼容的方式工作類:

class TodoView extends Backbone.View 
    tagName: 'div' 
    id: 'box' # don't do this if you have more than one TodoView on the page at once 
    className: 'red-box' 

todoItem沒有定義,因爲CoffeeScript的將包裝所有的你的代碼放在「立即執行的函數表達式」中,它可以防止泄漏變量到全局範圍(這是一件好事)。從文檔:

Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.

如果您想要檢查局部變量,請在Chrome的調試器或Firebug中設置斷點。


我很擔心這樣的代碼:

_.template "... #{ print "checked" if status is "complete"} ..." 

什麼是print?你在哪裏定義了?對於這個問題,status在哪裏?你的意思是@status


最後,你沒有看到div的原因是,你永遠不會把它添加到DOM。 .render()呈現元素...但它不會自動將其插入到頁面上。你必須自己去做:

todoView.render() 
$('body').append(todoView.el) # (or wherever you want it to go)