After Render event on CompositeView with Backbone.Marionette

I have a Marionette CompositeView with a search bar and a dataset of results.

I would like to call a function when:

  • the search bar is displayed.
  • collection is not yet displayed.
  • this function cannot be called when rendering a collection.

I did it this way: (but the "afterRender" function is called twice)

// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
    // TEMPLATE
    template: Handlebars.compile(templates.find('#composite-template').html()),
    // ITEM VIEW
    itemView: App.Item.View,
    // ITEM VIEW CONTAINER
    itemViewContainer: '#collection-block',

    //INITIALIZE
    initialize: function() {        
        this.bindTo(this,'render',this.afterRender);
    },

    afterRender: function () {
        //THIS IS EXECUTED TWICE...
    }

});

How can i do this?

=========================== EDIT ======================== ============

I solved it this way, if you have an observation, please let me know.

// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({

    //INITIALIZE
    initialize: function() {        
        //this.bindTo(this,'render',this.afterRender);
        this.firstRender = true;
    },

    onRender: function () {
        if (firstRender) {
            //DO STUFF HERE..............
            this.firstRender = false;         

        }
    }

});
+5
source share
2 answers

Marionette provides a method onRenderbuilt into all its forms, so you can get rid of the call this.bindTo(this, 'render', this.afterRender):


// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
    // TEMPLATE
    template: Handlebars.compile(templates.find('#composite-template').html()),
    // ITEM VIEW
    itemView: App.Item.View,
    // ITEM VIEW CONTAINER
    itemViewContainer: '#collection-block',

    //INITIALIZE
    initialize: function() {        
        // this.bindTo(this,'render',this.afterRender); // <-- not needed
    },

    onRender: function () {
        // do stuff after it renders, here
    }

});

, , onRender, , .

, , .

... " ", emptyView .


NoItemsFoundView = ItemView.extend({
  // ...
});

CompositeView.extend({

  emptyView: NoItemsFoundView

});

, , , .


CompositeView.extend({

  onRender: function(){
    if (this.collection && this.collection.length === 0) {
      // do stuff here because the collection was not rendered
    }
  }

});
+11

onShow

Backbone.Marionette.ItemView.extend({
  onShow: function(){
    // react to when a view has been shown
  }
});

http://marionettejs.com/docs/marionette.view.html#view-onshow

+4

All Articles