Question

i've added an instance store to my backbone models. When i manually create an object with an id it works and returns either a new or the already existing model. How can i integrate this functionality into backbone collections as well. Can you give me a hint, which method/methods i have to override?

My instance store code looks like this:

define(function(require) {
    var Backbone = require('backbone');
    return Backbone.Model.extend({
        constructor: function(attributes, options) {
            var id = attributes ? attributes.id : undefined;
            if(this.store[id])
                return this.store[id];
            Backbone.Model.prototype.constructor.apply(this, arguments);
            if(id)
                this.store[id] = this;
            this.count[id] = this.count[id] ? this.count[id] + 1 : 1;
        }
    });
});

I am thankful for any idea or hint!

Was it helpful?

Solution

Ok, well i've found my stupid mistake.

If someone is interested in this kind of solution:

There is nothing wrong with overriding the constructor like i did. It works like a charm. You do not have to override any other methods in Backbone.

But you have to set the model-property of the collection correctly. That was my bug. I didn't.

define(function(require) {
    var Base = require('collections/base'),
        Category = require('models/category');

    return Base.extend({
        model: Category, //<-- Important!
        url: function() {
            return App.serverUrl + 'categories';
        },
        initialize: function() {
            this.fetch();
        }
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top