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

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.


If you happen to be using Marionette, Marionette adds show and render events on views. See this StackOverflow question for an example.

On a side note, Marionette adds a lot of other useful features that you might be interested in.


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'); 
    } 
});

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.

Tags:

Backbone.Js