Ben
Ben

Reputation: 5361

Backbone - Clean/efficient way to wait for multiple events to be fetched before triggering event

I have a collection that I need to manipulate, but I need to wait for a model to be fetched before doing so. Can someone suggest a clean way to accomplish this? Is there a promise-like way people do this with backbone collections/models?

All I can think of is something like:

initialize: ->
    @listenTo @model, 'sync', @modelFetched
    @listenTo @collection, 'sync', @collectionFetched

modelFetched: ->
    @isModelFetched = true
    if @isCollectionFetched
        doTheThing()

collectionFetched: ->
    @isCollectionFetched = true
    if @isModelFetched
        doTheThing()

I've seen posts like this one (Backbone.js: Elegant way to check if data ready and if the dataset is empty) that use jQuery deffered - my wrinkle is that my model and collection are fetched in a controller file that feeds into this file, which is my view which is why I've had listeners attached to them

Upvotes: 0

Views: 231

Answers (1)

Ben
Ben

Reputation: 5361

I ended up just doing the synced check on my render method.

initialize: ->
    @listenTo @model, 'sync', @render
    @listenTo @collection, 'sync', @render

render: ->
    @doTheThing() if @model.synced and @deploys.synced

Upvotes: 1

Related Questions