首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Backbone采集返回错误数据

Backbone采集返回错误数据
EN

Stack Overflow用户
提问于 2013-04-28 10:23:29
回答 1查看 222关注 0票数 0

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

code.js.coffee

代码语言:javascript
复制
window.Code =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}
  initialize: ->
   new Code.Routers.Todos();
   Backbone.history.start()

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

todos_router.js.coffee

代码语言:javascript
复制
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 -->集合

代码语言:javascript
复制
class Code.Collections.Todos extends Backbone.Collection
  url: '/todos'

todos_index.js.coffee

代码语言:javascript
复制
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的控制台输出如下

代码语言:javascript
复制
Todos {length: 0, models: Array[0], _byId: Object, constructor: function, url: "/todos"…}
_byId: Object
_events: Object
length: 1
models: Array[1]
__proto__: ctor

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-28 23:14:44

我在获取集合时触发reset事件时遇到了一些问题。您是否对正在重置的集合特别感兴趣,或者只是在fetch完成了从API中检索数据的操作时才感兴趣?如果是后者,请在您的视图中尝试以下代码:

todos_index.js.coffee

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
class Code.Views.TodosIndex extends Backbone.View
  template: JST['todos/index']

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

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

作为第二个建议,您可能希望将@集合下推到视图中,而不是将其保留在路由器中,除非您需要在视图之间重用该集合。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16258899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档