Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js Build complex model (models into a model)

Is there a way to built more complex Model in Backbone.js, let me explain by an example :

This is a Json Session object :

{
    id: "17",
    notes: "",
    start: "2012-10-18T15:57:41.511Z",
    end: "2012-10-18T19:22:31.875Z",
    sessionType: {
        id: "1",
        name: "Life Style",
    }
}

When retrieving a Session Object from the server, I would like to have a SessionType Backbone.Model in order to add some business logic around this object.

So far I'm only able to retrieve an Object Session with a dummy SessionType, I can't add any logic on it because It doesn't belong to any Backbone model.

like image 981
Nicolas Henin Avatar asked Jan 29 '26 01:01

Nicolas Henin


2 Answers

You can try this:

window.SessionType = Backbone.Model.extend({

    initialize:function () {
    },

});

Then in your session model, have a method:

window.Session = Backbone.Model.extend({

    initialize:function () {
    },

    getSessionType () {
        return new SessionType(this.get('sessionType'));
    }

});

Now you can call the getSessionType() method which returns a model that can have your logic.

like image 120
Amulya Khare Avatar answered Jan 30 '26 14:01

Amulya Khare


@Amulya is 100% correct. However, if you want the Session Model without having to call getSessionType(), I would look at using the the built in parse method and creating your model from there.

If your Session model is related to your model, I would look at using Backbone Relational. Since Backbone does not handle relationships, the plugin listed above does a fine job in filling the gap without too much manual labour.

like image 23
TYRONEMICHAEL Avatar answered Jan 30 '26 16:01

TYRONEMICHAEL