For efficiency, you often want to get data for related records at the same time. The jquery.model.assocations.js plugin lets you do this.
Lets say we wanted to list tasks for contacts. When we request our contacts, the JSON data will come back like:
[
{'id': 1,
'name' : 'Justin Meyer',
'birthday': '1982-10-20',
'tasks' : [
{'id': 1,
'title': "write up model layer",
'due': "2010-10-5" },
{'id': 1,
'title': "document models",
'due': "2010-10-8"}]},
...
]
We want to be able to do something like:
var tasks = contact.attr("tasks");
tasks[0].due //-> date
Basically, we want attr("tasks") to
return a list of task instances.
Associations let you do this. Here's how:
First, create a Task model:
$.Model.extend("Task",{
convert : {
date : function(date){ ... }
},
attributes : {
due : 'date'
}
},{
weeksPastDue : function(){
return Math.round( (new Date() - this.due) /
(1000*60*60*24*7 ) );
}
})
Then create a Contact model that 'hasMany' tasks:
$.Model.extend("Contact",{
associations : {
hasMany : "Task"
},
...
},{
...
});
Here's a demo of this in action:
You can customize associations with the belongsTo and hasMany methods.