Ruby on rails 3 Backbone.js Collection.models不工作
我有一个Rails项目,使用Backbone.js和HAML作为客户端模板语言 在app/assets/views/meeting.coffee文件中:Ruby on rails 3 Backbone.js Collection.models不工作,ruby-on-rails-3,backbone.js,backbone.js-collections,hamlc,Ruby On Rails 3,Backbone.js,Backbone.js Collections,Hamlc,我有一个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))
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')
要工作该方法是异步的(即,它是幕后的AJAX调用),因此当您尝试在视图中使用它时,@collection.fetch()
没有从服务器返回任何内容。然而:
选项哈希将成功
和错误
回调作为参数传递给(收集、响应)
。当模型数据从服务器返回时,集合将重置
因此,您可以使用回调:
render: ->
@collection.fetch(
success: (collection, response) =>
@$el.html(@template(collection: @collection))
@
或者,您可以将视图的渲染
绑定到集合的重置
事件:
class window.MeetingIndex extends Backbone.View
template: JST['meeting/index']
initialize: ->
@collection.on('reset', @render)
@collection.fetch()
render: =>
@$el.html(@template(collection: @collection))
@
然后,视图的initialize
中的fetch
调用将在从服务器返回内容时间接触发适当的render
调用。如果您的模板知道如何处理空集合,那么这种方法最为有效,也许它可以检测到空集合并显示“正在加载”消息,或者只是说“还没有任何内容”