我是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
以「未定義」出現。
感謝您的任何幫助,你可以給!