To begin without the use of promises, beginners to Backbone end up writing smelly code like this:
First of all, I'm not a fan of articles that tell you a piece of code is bad without explaining why. The code above is particularly frustrating because it doesn't handle the use case where you fetch a collection off the server, but only to see that the collection is still empty. What does this lead to? An (albeit, relatively slow) infinite loop.
Which leads to the following kludge:
Calling that method adds an unrelated property as a side effect, which might lead to future bugs, especially if you have other methods
that need to follow the same logic as
A better way is to create an abstraction for your app to work with getting data from the server is to 1) leave the data management to another object and 2) use promises:
This lets you write refactor your
showAnimals code above:
While this is a great start to abstracting data management, one particular problem is that the signature (specifically, the return values)
getAnimals method is inconsistent. When the
fetch is returned, the object that is passed into the queued
dones is different
(it resolves with the ajax response) then when the created Deferred is returned, therefore:
It would be interesting to create a library that abstracts this elegantly for you using namespacing, but I can see issues come up in handling object permissions of data management without touching the Backbone.View class. In the Ember.js framework, all of the ORM-like abilities is abstracted in Ember-Data. and they do a pretty solid job of securing permissions.