Erik
Erik

Reputation: 14750

How to store data structure in Backbone?

I have the following data structure:

var data {
   'type_1' : [
       [
          {}, {}, {}
       ],
       [
          {}, {}
       ]
   ],
   'type_2': [
       [
          {}, {}
       ]
   ]
   ...
};

From the code above:

  1. type_{n} - is unique
  2. Each type can store array of arrays that can store simple objects with data

May you advise how can I construct my Models and Collections according this schema, so what should I use for models and collections? Thanks.

Upvotes: 0

Views: 164

Answers (1)

Ulug'bek
Ulug'bek

Reputation: 2832

It seems as if your data is model and each type_{n} is collection, but in backbone we couldn't write so. If I were you, I would do something like this:

coll = [
          {}, {}, {}
       ],// first collection
       [
          {}, {}
       ]// second collection

because it adds the second collection to the first, they are considered as one collection. So I will make a model from both collections. In short, do it yourself through the code:

var SimpleModel = Backbone.Model.extend({});

var SimpleCollection = Backbone.Collection.extend({ model: SimpleModel});
var SubModel = Backbone.Model.extend({
    default: {
        coll: new SimpleCollection()
    }
});
var SubCollection = Backbone.Collection.extend({ model: SubModel});
var ParentModel = Backbone.Model.extend({});

I used following code from browser command line to check it, maybe it is helpful for you too:

var s1 = new SimpleModel({"name":"n1"});
var s2 = new SimpleModel({"name":"n2"});
var s3 = new SimpleModel({"name":"n3"});
var c1 = new SimpleCollection();
c1.add(s1);
c1.add(s2);
var c2 = new SimpleCollection([s1,s2,s3])
var ss1 = new SubModel({"col" : c1});
var ss2 = new SubModel({"col" : c2});
var cc1 = new SubCollection([ss1,ss2]);
var cc2 = new SubCollection([ss1]);
var p1 = new ParentModel({"type_1": cc1, "type_2" : cc2});
JSON.stringify(p1);

Upvotes: 1

Related Questions