Backbone Collection返回错误的数据

时间:2013-04-28 02:23:29

标签: javascript ruby-on-rails backbone.js

嗨我有骨干应用程序如下:

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 - >集合

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

todos_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))

现在的问题是当我在模板上渲染集合以获得长度时,即使数据库上有1条记录,它仍然会给我结果0。我在这做错了什么? this.collection的控制台输出如下

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

谢谢!

1 个答案:

答案 0 :(得分:0)

我在使用集合提取时触发reset事件时遇到了一些麻烦。您是否对 reset 的集合感兴趣,或者您对fetch完成从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向下推入视图而不是将其保留在路由器中,除非您需要跨视图重复使用该集合。