Loading bar in Backbone

2019-02-21 06:06发布

I want to show a loading message/icon until all the items in the list have been rendered.

Here is the jsfiddle with my example: http://jsfiddle.net/9R9zU/58/

I've tried to add a div with a loading bar in the Feed section, but it doesn't work.

How can I show a loading message before all the book views are rendered in the book list view:

app.BookListView = Backbone.View.extend({
    el: '.feed',
    initialize: function() {
    this.render();
    this.listenTo( this.collection, 'add', this.renderBook );

2条回答
不美不萌又怎样
2楼-- · 2019-02-21 06:47

Here's a working example: http://jsfiddle.net/aJfUx/1/

render: function() {
    // Make this loading icon/message whatever you want
    this.$el.html("<i class='icon-spin icon-refresh loading-icon' />");

    this.collection.each(function( item ){
        this.renderBook( item );
    }, this);
    this.$el.find(".loading-icon").remove();

}

And here's an example that uses setTimeout to artificially add some loading time so you can see that spinner spin!

http://jsfiddle.net/7ddXM/

查看更多
Juvenile、少年°
3楼-- · 2019-02-21 06:54

In theory you need to fetch some content asynchronously from somewhere to display the loader. A loading is needed to show the user that you are actually fetching the content and that the UI is not dead. In that fiddle even if you got it working you won't be able to see it because the collection is bootstrapped and you are not fetching anything.

This simulates that (updated your fiddle):

app.BookListView = Backbone.View.extend({
  el: '.feed',
    initialize: function() {
      this.loader();
      this.listenToOnce( this.collection, 'sync', this.render); // or listenTo ?
      this.listenTo( this.collection, 'add', this.renderBook );

      // this simulates the fetching...
      // It's not really needed
      var self = this;
      setTimeout(function(){
          self.collection.trigger('sync');
      }, 3000)

    },
    loader: function(){
        this.$el.html('<div>Loading...</div>')
    },
  render: function() {
        this.$el.empty();
    this.collection.each(function( item ){
      this.renderBook( item );
    }, this);

  },
  renderBook: function ( item ) {
    var bookview = new app.BookView ({
      model: item
    });            
    this.$el.append( bookview.render().el );
  } 
});
查看更多
登录 后发表回答