我有一个Rails项目,Backbone.js和HAML作为客户端模板语言。
在文件app / assets / views / meeting.coffee中:
class window.MeetingIndex extends Backbone.View
template: JST['meeting/index']
render: ->
@collection.fetch()
@$el.html(@template(collection: @collection))
this
在文件app / assets / javascripts / templates / meeting / index.hamlc
中- console.log(@collection.length) # prints 0 in console
- console.log(@collection.models) # prints [] in console
- console.log(@collection.at(0)) # prints undefined in console
- window.x = @collection
如果我去浏览器控制台,我得到:
x.length # returns 2
x.models # returns [Meeting, Meeting]
x.at(0) # returns Meeting object
如果我可以访问.hamlc文件中的@collection变量,因为我将它分配给window.x.为什么我不能从.hamlc文件中访问@collection项目?
我需要像
这样的东西- for model in @collection.models
%p= model.get('landlord_id')
%p= model.get('tenant_id')
%p= model.get('at')
工作
答案 0 :(得分:3)
Collection#fetch
方法是异步的(即它是幕后的AJAX调用),因此当您尝试在视图中使用它时,@collection.fetch()
没有从服务器返回任何内容。但是:
选项哈希需要
success
和error
个回调,这些回调将作为参数传递(collection, response)
。当模型数据从服务器返回时,集合将重置。
所以你可以使用回调:
render: ->
@collection.fetch(
success: (collection, response) =>
@$el.html(@template(collection: @collection))
@
或者您可以将视图的render
绑定到集合的reset
事件:
class window.MeetingIndex extends Backbone.View
template: JST['meeting/index']
initialize: ->
@collection.on('reset', @render)
@collection.fetch()
render: =>
@$el.html(@template(collection: @collection))
@
然后视图fetch
中的initialize
调用会在从服务器返回某些内容时间接触发正确的render
调用。如果您的模板知道如何处理空集合,这种方法效果最好,也许它可以检测到空集合并显示“加载”消息,或者只是说“此处没有”。