In backbone.js, I want to do:
initialize: =>
@collection.on("add", @appendModel(model)) # <- how to correctly write it?
render: =>
# do some render
@collection.each(@appendModel())
appendModel: (model) ->
# append model to $el
Currently, i have @collection.on("add", @render), but that redraws the whole collection. I want to just fire appendModel(), but I’m not sure how to pass the model in the argument in this case.
In your example you are first invoking the
@appendModelmethod with an argumentmodel, and then passing the return value tocollection.on:You need to pass a reference to the method instead:
The caller (in this case Backbone) will pass the argument to the method for you.
You might also need to pass
this(or@) as a third argument to thecollection.onmethod. This is the context argument which tells Backbone that when the callback is executed, thethiscontext should be set tot that value:Or because you’re using coffeescript, you can just skip that bit and define the
@appendModelmethod with the fat arrow notation, which will ensure that thethiscontext is bound to your view: