Backbone relation example

by rjzaworski

HTML

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

JavaScript

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

// A collection of posts
var postCollection = Backbone.Collection.extend({
    model: post
});

// A blog that includes both a bunch of posts and the user
// who writes them
var blog = Backbone.Model.extend({

    // ...
    initialize: function () {

        var self = this;

        this.posts = new postCollection(this.get('posts'));
        this.posts.url = function () {
            return self.url() + '/posts';
        };
    },

    // ...
    urlRoot: '/blog/'
});

// The kind of data that a JSON GET request to the /blog/:id
// endpoint might return
var attributes = {
    id: 42,
    posts:[
        {id: 13, title: 'hello, world'}
    ]
}

// A blog model based on the attributes
b = new blog(attributes);

// A test to make sure
b.posts.each(function (post) {
    console.log(post.url());
});