Search code examples
javascriptjquerybackbone.js

Show loading canvas before Backbone view completely rendered


I'm doing backbone project with underscore.js and require.js. And I've got stuck with showing a loading image using http://heartcode.robertpataki.com/canvasloader/ before everything in my view is completely rendered.

I found a solution, using $(window).load() , but It did not work for me.

Here is my view :

render: function(options){
        var _banner = _.template(BannerTem);
        $(window).load(function() {
           this.loadingStuff();
        });
        $(this.el).html(_banner({type : this.options.type}));
        return this;
}

loadingStuff() is called after the backbone view rendered. But what I am trying to do here is to call loadingStuff() method before a view is rendered completely.

Any ideas would be appreciated.


Solution

  • In this simple fiddle you can find similar behavior:

    var loader = function(selector) {
        return new CanvasLoader(selector);
                cl.setColor('#877387'); // default is '#000000'
                cl.setDiameter(41); // default is 40
                cl.setDensity(50); // default is 40
                cl.setRange(1.1); // default is 1.3
                cl.setSpeed(4); // default is 2
    } 
    
    var TestView = Backbone.View.extend({
        initialize: function () {
            this.loader = loader("container");
            this.loader.show();
        },
        template: _.template($('#test-view').html()),
        el: '#container',
        render: function () {
            var template = this.template({name: "Test Product", description: "Test description"});
            this.$el.append(template);
            this.loader.hide();
        }
    })
    
    
    var testView = new TestView();
    setTimeout(function() {testView.render();}, 3000 );
    

    Timeout function needed to simulate interactions with remote, or time consuming operations when rendering. This example simply could be adopted for your structure with controller's action. Mask the container when action called and unmask it when loading finished.

    Be sure to kill loader instance if you don't need it anymore.