有点古怪的一...Backbone.js的不通过收集迭代
我有收集:
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)
不做任何事情,不会错误或通过任何东西。它只是没有做任何事情。我正试图从集合中提取数据!但它不会...
检查http://stackoverflow.com/questions/8413500/backbone-js-populating-a-collection/ 8415515#8415515或http://stackoverflow.com/questions/11459244/backbone-js-empty-array-attribute/11463190#11463190 – nikoshr 2012-07-19 14:15:34
btw:为什么'$ this = ...'当你有'this。$ el '。我建议阅读backbone.js文档。 – jakee 2012-07-19 14:35:35
并清除nikoshr的答案:collection.fetch是'异步的',并且您可能在提取返回之前在初始化方法中呈现您的视图,因此该集合为空。 console.log是'wtfsynchronous',所以它不管将收集记录为已填充。你必须做的是将渲染方法绑定到集合的重置事件,以确保视图在集合被填充后也被渲染 – jakee 2012-07-19 14:43:41