2012-04-15 72 views
1

我是Backbone.js的全新品牌,我正試圖將其整合到我當前的Rails應用程序中。我正在關注來自railscasts的教程,但我在集成它們時遇到了麻煩。基本上,我正在嘗試調用我的資源(項目),並將它們顯示在頁面上。我的路由器看起來如下:Rails的Backbone.js,@collection是'undefined'?

class Placeholder.Routers.Projects extends Backbone.Router 
    routes: 
    '': 'index' 
    'projects/:id':'show' 

    initialize: -> 
    @collection = new CIS196Project.Collections.Projects() 
    @collection.fetch() 

    index: -> 
    view = new Placeholder.Views.ProjectsIndex() 
    $('#container').html(view.render().el) 

    show: (id) -> 
    alert "Project #{id}" 

,我的看法是這樣的:

class Placeholder.Views.ProjectsIndex extends Backbone.View 

    template: JST['projects/index'] 

    initialize: -> 
    document.write(@collection) 
    @collection.on('reset', @render, this) 

    render: -> 
    $(@el).html(@template(projects: @collection)) 
    this 

我全部大多來自教程了直。我添加了document.write(@collection)進行測試。

在加載頁面時,我得到的錯誤:

projects_index.js:17 Uncaught TypeError: Cannot call method 'on' of undefined

我成功地使fetch()在路由器,因爲在我的日誌中,GET請求成功通過,並在嘗試了鍍鉻的控制檯,fetch應該返回一個大小爲1的數組,但是相反,它會給出這個錯誤,然後從它的控制器加載默認的rails視圖(我也不知道爲什麼發生這種情況,我有一個定義好的模板,但是,當它拋出這個錯誤時,它只是恢復到以前,除非我稱之爲document.write)。在致電document.write後,@collection以「未定義」出現。

感謝您的任何幫助,你可以給!

回答

2

你正在創建您的收藏在你的路由器的一個實例變量:

class Placeholder.Routers.Projects extends Backbone.Router 
    #... 
    initialize: -> 
    @collection = new CIS196Project.Collections.Projects() 
    #... 

,但你千萬不要給人收集到您的視圖:

index: -> 
    view = new Placeholder.Views.ProjectsIndex() 
    #... 

如果提供了收集到您的視圖:

index: -> 
    view = new Placeholder.Views.ProjectsIndex(collection: @collection) 
    #... 

那麼你將有一個collection實例變量在你看來。

fine manual

constructor/initializenew View([options])

[...] There are several special options that, if passed, will be attached directly to the view: model , collection , el , id , className , tagName and attributes .

因此,只要指定collection選項,當您實例化視圖足以在視圖中獲得@collection

順便說一句,console.log(@collection)document.write(@collection)一個好主意,document.write具有不幸的副作用(如有時擦除整個頁)和console.log會產生較多的可讀的輸出。