Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js event after view.render() is finished

Tags:

backbone.js

Does anyone know which event is fired after a view is rendered in backbone.js?

like image 348
schlubbi Avatar asked Mar 20 '12 16:03

schlubbi


3 Answers

I ran into this post which seems interesting

var myView = Backbone.View.extend({ 

    initialize: function(options) { 
        _.bindAll(this, 'beforeRender', 'render', 'afterRender'); 
        var _this = this; 
        this.render = _.wrap(this.render, function(render) { 
            _this.beforeRender(); 
            render(); 
            _this.afterRender(); 
            return _this; 
        }); 
    }, 

    beforeRender: function() { 
       console.log('beforeRender'); 
    }, 

    render: function() { 
        return this; 
    }, 

    afterRender: function() { 
        console.log('afterRender'); 
    } 
});
like image 192
abritez Avatar answered Nov 11 '22 14:11

abritez


Or you can do the following, which is what Backbone code is supposed to look like (Observer pattern, aka pub/sub). This is the way to go:

var myView = Backbone.View.extend({ 
    initialize: function() {  
        this.on('render', this.afterRender);

        this.render();
    },

    render: function () {  
        this.trigger('render');
    },

    afterRender: function () {
    }
});

Edit: this.on('render', 'afterRender'); will not work - because Backbone.Events.on accepts only functions. The .on('event', 'methodName'); magic is made possible by Backbone.View.delegateEvents and as such is only available with DOM events.

like image 24
pilau Avatar answered Nov 11 '22 15:11

pilau


As far as I know - none is fired. Render function is empty in source code.

The default implementation of render is a no-op

I would recommend just triggering it manually when necessary.

like image 18
Arnis Lapsa Avatar answered Nov 11 '22 16:11

Arnis Lapsa