2
votes

I am building a web app using backbone.js as an MVC framework. I am struggling in designing my models. I have one parent/main object but it is quite complex/nested in nature i.e over 50 attributes and some nesting going on. What i am struggling with is:

I have something like:

    {section1:{
      key1:"value1", 
      key1:"value2"}, 
     section2:{
      key1:"value1", 
      key1:"value2"}
    }

Should i flatten the object out like:

    {section1_key1:"value1",
     section1_key2:"value2",
     section2_key1:"value1",
     section2_key2:"value2"
    }

or should I:

  1. use the backbone-nested plug-in and pass in the large nested JSON object as is?
  2. or create separate models for each section and nest somehow within the parent model.
  3. or simply create models for the child objects and not worry about the nesting and add some type of reference

Suggestions appreciated.

1
Also there's this from the FAQ: documentcloud.github.com/backbone/#FAQ-nested - tkone

1 Answers

3
votes

I'm struggling on this right now as well.

I'm leaning towards option 2.

I have each of the nested sections built out into separate models, and creating an interface similar to SQLObject in Python (or really any ORM)

So given a simple blog post idea:

var Tag = Backbone.Model.extend({
    defaults: {
        name: ''
    },
    validate: function(atts){
        if(!atts.name || atts.name.length < 2){
            return "You must provide a name that's longer than 2 characters";
        }
    }
});

var TagList = Backbone.Collection.extend({
    model: Tag
})

var Entry = Backbone.Model.extend({
    defaults: {
        author: "Todd",
        pub_date: new Date(),
        content: "",
        title: "",
        tags: new TagList()
    },
    add_tag: function(tag){
        var tag_collection = this.get('tags');
        tag_collection.add({name: tag});
        this.set({tags: tag_collection});
    },
    remove_tag: function(tag){
        tag.destroy();
    },
    tags: function(){
        return this.get('tags').models;
    }
});

An alternate idea would to let initialize handle the de-nesting and creation and adding of items to the collection that is then stored as a property on that model.