【发布时间】:2012-11-29 07:45:10
【问题描述】:
有点奇怪……
我有收藏:
class Store.Collections.Product extends Backbone.Collection
url: '/api/products'
model: Store.Models.Product
与视图:
class Store.Views.Origin extends Backbone.View
initialize: ->
@collection = new Store.Collections.Product()
@collection.fetch()
@model.bind('change:formatted', @render, this);
@render()
events:
'change [name=origin]': 'setOrigin'
el: =>
@options.parent.$('.origin-input')[0]
template: JST["backbone/templates/shapes/product"]
render: ->
$this = $(this.el)
$this.html(@template(model: @model.toJSON(), errors: @model.errors))
console.log(@collection)
@collection.each(@appdenDropdown)
@delegateEvents()
this
appdenDropdown: (product) ->
console.log("append trigger")
#view = new Store.Views.Products(model: product)
#$('#history').append(view.render().el)
使用模板:
<div id="history"></div>
该系列作品...
console.log(@collection)
显示数据!然而
@collection.each(@appdenDropdown)
不做任何事情,不出错,或通过任何事情。它只是没有做任何事情。我正在尝试从集合中提取数据!但它不会...
【问题讨论】:
-
顺便说一句:当你有
this.$el时,为什么还要$this = ...。我建议通读backbone.js 文档。 -
并明确 nikoshr 的答案:collection.fetch 是
asynchronous并且您可能在 fetch 返回之前在 initialize 方法中呈现您的视图,因此集合是空的。 console.log 是wtfsynchronous,因此它无论如何都会将集合记录为已填充。您需要做的是将渲染方法绑定到集合的重置事件,以确保在填充集合后视图也被渲染 -
谢谢,看看,集合不是空的,因为它在我仅用于测试的 console.log 中显示了它的数据
-
console.log 显示填充集合在我链接的第二个答案中进行了解释。总结:console.log 耍花招,在记录之前克隆集合,看看你得到了什么