Backbone.js 在回调中使用集合呈现主干视图
以下是我正在使用的视图:Backbone.js 在回调中使用集合呈现主干视图,backbone.js,coffeescript,Backbone.js,Coffeescript,以下是我正在使用的视图: class Raffler.Views.EntriesIndex extends Backbone.View template: JST['entries/index'] initialize: -> @collection.on('reset', @render, this) render: -> Raffler.entries = @collection $(@el).html(@template(eventSou
class Raffler.Views.EntriesIndex extends Backbone.View
template: JST['entries/index']
initialize: ->
@collection.on('reset', @render, this)
render: ->
Raffler.entries = @collection
$(@el).html(@template(eventSource: (start, end, callback) ->
console.log @collection # = undefined
callback(Raffler.entries.events(start, end))
))
我必须将window.Raffler属性分配给我的集合才能在回调中使用它。有没有一种很好的方法可以使用回调(@collection.events(start,end))?如果你
这个.bindAll(这个),在初始化
的内部
然后此.collection
应该在coffeescript中的渲染内部工作,如果使用“胖箭头”(=>
)操作符而不是->
,则回调函数将在创建它的范围内绑定到此(
)。这意味着您可以在回调中使用@collection,@将正确引用您的EntrieIndex,因此您的渲染函数可以如下所示:
render: ->
$(@el).html(@template(eventSource: (start, end, callback) =>
console.log @collection # == your EntriesIndex collection
callback(@collection.events(start, end))
))
看
我上面的建议只有在此
(@
)引用了render中的EntriesIndex时才有效,因此我相信您可能也必须按照Abraham的建议执行,并确保将@绑定到render函数中的EntriesIndex。将此项添加到初始化:
_.bindAll this
知道Coffeescript的人可以纠正我的语法错误:)