Backbone relation example

by paulL

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>

JavaScript

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

var postCollection = Backbone.Collection.extend({
    model: post
});

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

var blog = Backbone.Model.extend({

    defaults: {
        user: null,
        posts: []
    },

    initialize: function () {

        var self = this;

        // create a faux-belongsTo relationship:
        this.user = new user(this.get('user'));

        // could set reverse hasMany relationship if `this.user` 
        // has a `blogs` attribute containing a backbone collection:
        //
        // this.user.blogs.add(this);

        // create a faux-hasMany relationship:
        this.posts = new postCollection(this.get('posts'));
        this.posts.url = function () {
            return self.url() + '/posts';
        };

        // could set reverse hasOne/belongsTo relationship, if 
        // `this.posts` need to know where they belong:
        //
        // this.posts.each(function (post) { post.blog = self; });
    },

    urlRoot: '/blog/'
});

var attributes = {
    id: 42,
    posts:[
        {id: 13, title: 'hello, world'}
    ],
    user: { id: 10 }
}

b = new blog(attributes);
b.posts.each(function (post) {
    console.log(post.url());
});