Lorraine Bernard
Lorraine Bernard

Reputation: 13410

The initial events that the composite view binds to

According the Composite View documentation in a Composite View the events reset, remove and add are already bind to the collection.

Said that, why do I need to bind the reset event to render my CompositeView?

P.S.:
I am using Backbone.Marionette v0.9.1
Please see the code for more details (1), (2)
Actually the problem is about serializeData, because when the render function is called from initialEvents the variable has_message is set to zero. so the ul.messages is not defined in the template. How should I fix it?


(1)

var CompositeView = Marionette.CompositeView.extend({

    template: CompositeTemplate,

    itemView: messageView,

    initialize: function () {
        this.collection = new MessageCollection();
        this.collection.fetch();

        this.bindTo(this.collection, 'reset', this.render);
        // deleting the previous line 
        // I cannot see the collection rendered after the fetch.
    },

    serializeData: function () {
        return {
            has_messages: this.collection.length > 0
        };
    },


    appendHtml: function (collectionView, itemView) {
        collectionView.$el.find('ul.messages').append(itemView.el);
    }

});

(2)

// Template


{{#if has_messages }}
    <!-- list messages -->
    <ul class="list messages"></ul>
{{else}}
    no messages
{{/if}}

Upvotes: 1

Views: 1291

Answers (1)

Derick Bailey
Derick Bailey

Reputation: 72868

The need to bind to "renset" yourself is because composite view binds the reset event to the collection rendering, not the entire composite view:

https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.compositeview.md#events-and-callbacks

The problem with your serializeData function is probably caused by a context problem. You need to change your event binding to this:

this.bindTo(this.collection, 'reset', this.render, this);

This will bind the context of the view with the event.

Upvotes: 2

Related Questions