Last Updated: February 25, 2016
·
1.255K
· lowerkey

One-To-Many Relationships in Backbone.js with localStorage

Writing a program with what amount to nested collections, I ran into a problem: Backbone.js doesn't have nested collections.

Here's a little workaround:

Name = Backbone.Model.extend({
    defaults: {
        value: '',
        from: '',
        until: '',
    },
});

createNameCollection = function(id){
    var NameCollection = Backbone.Collection.extend({
        model: Name,
        localStorage: new Store('names_' + id);
    });

    return new NameCollection();
};

Now each entity that requires a NameCollection can access it by calling createNameCollection with its own id as a parameter.

In a view, this might look like...

var names = createNameCollection(this.model.id);
names.fetch();
// now you're ready to operate on the NameCollection.

Happy nesting!