Backbone relation example
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
JavaScript
var post = Backbone.Model.extend({
});
var postCollection = Backbone.Collection.extend({
model: post,
url: "blah/",
});
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 = '/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());
});