Model lists are useful for:
It's pretty common to deal with multiple items at a time. List helpers provide methods for multiple model instances.
For example, if we wanted to be able to destroy multiple contacts, we could add a destroyAll method to a Contact list:
$.Model.List.extend("Contact.List",{
destroyAll : function(){
$.post("/destroy",
this.map(function(contact){
return contact.id
}),
this.callback('destroyed'),
'json')
},
destroyed : function(){
this.each(function(){
this.destroyed();
})
}
});
The following demo illustrates this. Check multiple Contacts and click "DESTROY ALL"
The 'easy' way to add a model to an element is simply inserting the model into the view like:
<div <%= task %>> A task </div>
And then you can use $('.task').models().
This pattern is fast enough for 90% of all widgets. But it does require an extra query. Lists help you avoid this.
The [jQuery.Model.List.get get] method takes elements and uses their className to return matched instances in the list.
To use get, your elements need to have the instance's identity in their className. So to setup a div to reprsent a task, you would have the following in a view:
<div class='task <%= task.identity() %>'> A task </div>
Then, with your model list, you could use get to get a list of tasks:
taskList.get($('.task'))
The following demonstrates how to use this technique: