dagda1
dagda1

Reputation: 28780

Correct Backbone.js collection event for when async data is retrieved

I want to render a view when a collection has been loaded asynchronously from the remote server. I have the following collection class

class BusinessUnits extends Backbone.Collection
  model: BusinessUnit

  parse: (units) ->
    units

And then my view I was doing this:

  load: (businessUnits) =>
    @collection = businessUnits
    @collection.fetch()
    @render()

Obviously render() will be invoked before the fetch has been completed.

Is there a backbone.js event that is fired whenever the collection is fetched or would I be better firing my own?

This seems like a very common scenario. How do people handle this type of situation?

Upvotes: 0

Views: 3003

Answers (1)

Thilo
Thilo

Reputation: 262494

I think the "reset" event is what you are looking for.

"reset" (collection) — when the collection's entire contents have been replaced.

This will be triggered after the fetch completes.

load: (businessUnits) =>
    @collection = businessUnits
    @collection.bind 'reset', => @render()
    @collection.fetch()

Upvotes: 5

Related Questions