marionette.js view difference between onShow vs onRender?

addisu picture addisu · Jun 14, 2013 · Viewed 20.7k times · Source

I am new to Marionette.js and while I am refactoring my existing Backbone.js code, I noticed there are two callbacks on Marionette view (itemview) that looked to me similar, i.e. onRender and onShow. What is the difference and better way of using them ?

However, looking at source code, i think both "render" and "show" events are raised inside "view initialize".

constructor: function(){
    _.bindAll(this, "render");

    var args = Array.prototype.slice.apply(arguments);
    Backbone.View.prototype.constructor.apply(this, args);

    Marionette.MonitorDOMRefresh(this);
    this.listenTo(this, "show", this.onShowCalled, this);
}

Answer

John Bernardsson picture John Bernardsson · Dec 2, 2013

I think there is something not totally correct in Vitaliy's answer. The correct will be:

onShow : view itself doesn't trigger 'show' event. It triggers by a region. So it will not be called in some cases.

onRender : this method executes every time the view is rendered.

Note that 'onRender' being executed doesn't mean that the object is actually added to the DOM. It just means that it was just rendered (data filled the template, you have a this.$el to deal with, etc.)

On the other hand, if 'onShow' is called because the 'show' event has been triggered from a region, and as regions usually represent an element within the DOM, you might expect that when 'onShow' is called, the view is indeed added to the DOM.