1
votes

Im using Backbone 0.9.2 which still has the {add: true} on a fetch, and marionette 1.0.0.b4

So the scenario is that I have a collection rendered onto the screen on page load (this works great). Now I want to add to that collection with another fetch call.

From everything I understand, marionette.js overrides the add function with a reset function every time.

I've looked into the initializeEvents function and bound the "reset" event to my own event. Inside my event I call this.collection.add(); which works great except it doesnt render the data into the template because I havent called this.render(); yet.

This is where it gets sucky. So I call this.render(); and it renders the data. YAY! BUT, on next fetch this.render() resets the data (im guessing marionette has its own render function that always resets instead of adds)

initialEvents: function () {
        if (this.collection) {
            this.bindTo(this.collection, "add", this.addChildView, this);
            this.bindTo(this.collection, "remove", this.removeItemView, this);
            this.bindTo(this.collection, "reset", this.resetted, this);
        }
    },
    resetted: function (item, collection, options) {

        // this works, but doesnt render data into the template, just empty divs
        this.collection.add();

        // this.render() resets the collection.
        this.render();

    },

Item = collection (with all my data)
Collection  = {} (literally)
options = undefined

Yes I know resetted is the worst function name, but whatever, its sudo code.

I've also tried marionettes "collectionEvents", but found out these fire AFTER the render has happened.

1
UPDATE: I was parsing the collection response and resetting it in there. Im an idiot.dhechler

1 Answers

0
votes

On both a Backbone model and collection, there is a method that you can override called parse.

var B = Backbone.Collection.extend({
   ............,
   model: A,
   parse: function (data) {
       // manipulate your data here then return it
       return data;
   }
});

I use this functionality when I want to return multiple collections on the same call and save the data to a property of the collection.

var B = Backbone.Collections.extend({
    ..................,
    model: A,
    pagingCollection: {},
    parse: function(data) {
       this.pagingCollection = data.PageCollection;
       return data.CoreData;
    }
});