Layout, initialization, and rendering

I have an idea about the skeleton that subview loads. When I load a subview, I would like to show the loader when the fetch view requires data, and hide the loader when the view is ready for rendering.

I did something like this:

var appView = Backbone.View.extend({ showLoader: function() { // Code to show loader }, hideLoader: function() { // Code to hide loader  }, loadSubView: function() { this.showLoader(); var myView = new MySubView(); this.$el.html(myView.render().el); this.hideLoader(); } }); 

My subtask is currently loading the collection and implemented as follows:

 var mySubView = Backbone.View.extend({ initialize: function() { this.myCollection.fetch({ async: false }); }, render: function() { // Code to render } }); 

My subview loads the collection synchronously, because this is the only way to find out when my view is β€œready” for rendering, but I think this is not the best way to use Backbone.

What should I do?

+7
source share
1 answer

There are several ways to do this.

  • You can explicitly use the pubsub template. Something like that:

     var AppView = Backbone.View.extend({ showLoader: function() { console.log('show the spinner'); }, hideLoader: function() { console.log('hide the spinner'); }, loadSubView: function() { this.showLoader(); var subView = new SubView(); subView.on('render', this.hideLoader); this.$el.html(subView.render().el); } }); var SubView = Backbone.View.extend({ render: function() { console.log('a subView render'); this.trigger('render'); return this; } }); var appView = new AppView({el: $('body')}); appView.loadSubView(); 

    http://jsfiddle.net/theotheo/qnVhy/

  • You can attach a function to ajaxStart / ajaxStop events on the spinner itself:

     var AppView = Backbone.View.extend({ initialize: function() { var _this = this; this.$('#spinner') .hide() .ajaxStart(_this.showLoader) .ajaxStop(_this.hideLoader); } ... } 
  • Or you can use jQuery.ajaxSetup :

      var AppView = Backbone.View.extend({ initialize: function() { var _this = this; jQuery.ajaxSetup({ beforeSend: _this.showLoader, complete: _this.hideLoader, success: function() {} }); } ... } 
+15
source

All Articles