Skip to content

Displaying A "loading ..." Message For A Collection Or Composite View

markotom edited this page Nov 4, 2013 · 3 revisions

It's common to want to show a "loading ..." message of some sort - often with a spinning or animated icon to signify processing in the background. This is easy to do with a CompositeView or CollectionView in Marionette, when the items from the collection are still being loaded.

You can specify an emptyView to render when a collection has no items in it. The collection view will handle this automatically. Any time it sees the collection drop to zero items, it will render this empty view, which can be used to show your "loading" message.


LoadingMessageView = Backbone.ItemView.extend({
  template: "#loading-message-template"
});

ItemView = Backbone.ItemView.extend({
  template: "#normal-item-view"
});

MyCollectionView = Backbone.CollectionView.extend({
  emptyView: LoadingMessageView,
  itemView: ItemView,
  initialize: function () {
    this.listenTo(this.collection, 'sync', this.closeEmptyView);
  }
});

Then in your code, you can pass a collection that has not yet been loaded in to the view, show it, and then load it.


var col = new MyCollection();
var colView = new MyCollectionView({
  collection: col
});

App.someRegion.show(colView);

col.fetch();

This will render and show the collection view, displaying the loading message from the emptyView initially. When the collection finishes it's fetch, the "reset" event will trigger and the collection view will re-render with all of the items.