2013-04-28 28 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向下推入视图中,而不是将其保留在路由器中,除非您需要跨视图重新使用集合。