Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Model: Keep Collection when saving

I have a simple Backbone model that looks like this:

(function () {

    App.Company = Backbone.Model.extend({
        defaults: {},

        urlRoot: "/Contacts/Companies",

        initialize: function () {
            var contactPersons = this.get("ContactPersons") || [];

            this.set("ContactPersons", new App.ContactPersonCollection(contactPersons));
        }
    });

})();

Whenever I save the model to the server, the ContactPersons collection is reset to an Array.

Is it really necessary for me to manually turn it into a collection, after a model is saved?

UPDATE: This works as intended -- See answer for better approach (IMHO)

(function () {

    App.Company = Backbone.Model.extend({
        defaults: {},

        urlRoot: "/Contacts/Companies",

        initialize: function () {
            var contactPersons = this.get("ContactPersons") || [];

            if (_.isArray(contactPersons)) {
                this.set("ContactPersons", new App.ContactPersonCollection(contactPersons));
            }
        },

        parse: function (response) {

            if (response.ContactPersons && _.isArray(response.ContactPersons)) {
                response.ContactPersons = new App.ContactPersonCollection(response.ContactPersons);
            }

            return response;
        }
    });

})();
like image 518
MartinHN Avatar asked Aug 28 '26 09:08

MartinHN


1 Answers

When you send data back from the server, how are you handling the response? For example if you just send back a [{},{},{}] I don't think Backbone automatically knows to treat that as a collection. Thus, it sets the ContactPersons attribute as what it gets, your vanilla array.

What you can do, is override your set function inside your model which will take the array of objects passed in and write to the collection as proper. See this example:

set: function(attributes, options) {

    if (_.has(attributes, 'ContactPersons') && this.get("ContactPersons")) {
        this.get('ContactPersons').reset(attributes.ContactPersons);
        delete attributes.ContactPersons;
    }

    return Backbone.Model.prototype.set.call(this, attributes, options);
}

So basically as long as your server response is properly namespaced (response.ContactPersons) then after parsing it will pass your response to the set function. The collection data is treated specially as a collection. Here, I'm just reseting the collection that already exists with the new data. All your other model attributes should continue to be passed on to the original set().

UPDATE - Growing doubt about own answer

I haven't been able to get this question/answer out of my mind. It certainly works, but I'm becoming unconvinced that using a modified set() vs. just doing things in parse() is any better. If someone has some comments on the difference between using a modified set() vs. parse() with nested models, I'd really welcome the input.

like image 106
jmk2142 Avatar answered Aug 31 '26 00:08

jmk2142



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!