2013-04-28 50 views
0

嗨,我是有骨氣的應用程序如下:骨幹集合返回錯誤的數據

code.js.coffee

window.Code = 
    Models: {} 
    Collections: {} 
    Views: {} 
    Routers: {} 
    initialize: -> 
    new Code.Routers.Todos(); 
    Backbone.history.start() 

$(document).ready -> 
    Code.initialize() 

todos_router.js.coffee

class Code.Routers.Todos extends Backbone.Router 
    routes: 
     '': 'index' 
     'todos/:id': 'show' 

    initialize: -> 
     @collection = new Code.Collections.Todos() 
     @collection.fetch() 
    index: -> 
     view = new Code.Views.TodosIndex(collection: @collection) 
     view.render() 
     $('#container').html(view.el) 

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

todos.js.coffee - - > collection

class Code.Collections.Todos extends Backbone.Collection 
    url: '/todos' 

to dos_index.js.coffee現在

class Code.Views.TodosIndex extends Backbone.View 

    template: JST['todos/index'] 

    initialize: -> 


     this.collection.on('reset',this.render,this) 

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

的問題是,當我上呈現模板收集得到的長度,它仍然給我造成0即使有1條記錄數據庫。我在這裏做錯了什麼?這個.collection的控制檯輸出如下

Todos {length: 0, models: Array[0], _byId: Object, constructor: function, url: "/todos"…} 
_byId: Object 
_events: Object 
length: 1 
models: Array[1] 
__proto__: ctor 

謝謝!

+0

您使用的是哪個版本的Backbone? – 2013-04-28 02:45:56

+0

@ muistooshort在我的寶石文件上,我只是添加寶石的'backbone-on-rails' – d3bug3r 2013-04-28 02:48:30

+0

而且哪個版本的Backbone是使用?你的'render'被調用一次還是兩次? – 2013-04-28 02:55:45

回答

0

我在收集提取時觸發reset事件時遇到了一些問題。您是否對重置的集合感興趣,或者當抓取已完成從API中檢索數據的操作時,您是否只對此感興趣?如果是後者,試試這個代碼在您的視圖:

todos_index.js.coffee

class Code.Views.TodosIndex extends Backbone.View 
    template: JST['todos/index'] 

    initialize: -> 
    @collection.on 'sync', @render 

    render: => 
     $(@el).html(@template(todo: @collection)) 

有關更多信息,請參見the list of exposed events對每個事件觸發。還請注意,fetch方法takes a variety of boolean flags指定是否觸發某些事件。

如果你真的需要掛接到reset事件(也就是,你想知道什麼時候收集已騰空了),那麼你可以嘗試這樣的事:

todos_router.js .coffee

class Code.Routers.Todos extends Backbone.Router 
    routes: 
     '': 'index' 
     'todos/:id': 'show' 

    initialize: -> 
     @collection = new Code.Collections.Todos() 
     @collection.fetch 
      reset: true 
      silent: false 

    index: -> 
     view = new Code.Views.TodosIndex(collection: @collection) 
     view.render() 
     $('#container').html(view.el) 

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

todos_index.js.coffee

class Code.Views.TodosIndex extends Backbone.View 
    template: JST['todos/index'] 

    initialize: -> 
    @collection.on 'reset', @render 

    render: => 
     $(@el).html(@template(todo: @collection)) 

作爲輔助建議,您可能希望將@collection向下推入視圖中,而不是將其保留在路由器中,除非您需要跨視圖重新使用集合。