Reputation: 11008
Here is a view I am working with:
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))
))
I had to assign window.Raffler property to my collection to be able to use it in the callback. Is there a nice way of using something like callback(@collection.events(start, end))
?
Upvotes: 0
Views: 249
Reputation: 1609
In coffeescript, if you use the "fat arrow" (=>
) operator instead of ->
, your callback function will be bound to the this
(@
) in the scope in which it is created. This means you can use @collection within your callback and @ will properly refer to your EntriesIndex, so your render function can just look like this:
render: ->
$(@el).html(@template(eventSource: (start, end, callback) =>
console.log @collection # == your EntriesIndex collection
callback(@collection.events(start, end))
))
See http://coffeescript.org/#fat_arrow
My suggestion above will only work if this
(@
) refers to your EntriesIndex within render, so I believe you may have to do as Abraham suggested as well and make sure to bind @ to your EntriesIndex within the render function. Add this to initialize:
_.bindAll this
Someone who knows Coffeescript can correct me if I'm wrong on that syntax :)
Upvotes: 1
Reputation: 47893
Inside of initialize
if you this.bindAll(this);
then this.collection
should work inside of render
.
Upvotes: 1