documentcloud/backbone — pull request #1827 by tgriesser (2012-11-17 15:33:44+00:00)
Title: fetchModel - an API for lazy loading models from persisted collections

This pull request comes from a real world use case that I experience quite often in creating backbone apps. I like to prefetch as much data as possible for the page load, and keep my models/collections persisted (which is why I was big on getting something like `.dispose` added). While this approach can make the UI more responsive and lead to less server hits, it's also easier to end up in a bad data state.

For example:

```javascript
var view = new ItemView({
model: collections.items.get(1)
}).render();
```

In order for this to work, I need to know that a model with `id == 1` is already present in the collection, otherwise the use of an undefined model will be an issue.

I've ended up doing different things, in different places (maybe conditionally checking if the model is present in the `render`, maybe defaulting to an empty model in the `initialize`, etc.) and I felt like this is or should be a common enough use case to add this functionality.

The `fetchModel` function looks to assist in achieving this functionality, by adding something like a Backbone deferred model. If the model exists already it is immediately returned, with an optional `{refresh:true}` in the options to also call `.fetch` on the model to check the server for any updates. Otherwise, an empty model of the collection's type, with the requested id is returned, firing off a `fetch` request for the model. It's then easy to respond to a model that doesn't exist on the server, by passing an `error` callback in the `options`

```javascript
var Items = Backbone.Collection.extend({
url: '/items'
});

var items = new Items([{id:1, item:'Working'}]);

// this won't work.
var view = new Backbone.View({
item: items.get(2)
}).render();

// this will
var view = new Backbone.View({
item: items.fetchModel(2)
}).render();

```

I'm not sure if this is the best API for this - maybe `.get(1, {fetch:true})` would be better suited. But I'd really like to see something like this in the core, as I think it's something that would be helpful in a lot of cases.