The Backbone Basics
A basic single page application boils down to three distinct parts: Model, Collection and View.
The Model defines your class properties and methods. Here we define a class called Knot:
The Collection defines a list of class instances. Here we define a Collection called Knots:
First, you define which model the Collection will create a list of. Here, we also specify the collection’s data source using the URL property.
Here, the data source is deeply nested. You can use the parse method to intercept the data source and get the data in a more manageable state before creating your model instance.
Finally, we immediately execute the collection to get it ready for use in our single page application (SPA).
The View updates the User Interface (UI) with the data fetched from the collection:
First, we reset the knots collection. Next, we bind our View’s render method to our Collection’s add event. What this means is each time a Knot object is added to the Knots collections, we will call the Views render method to update the web application.
Then we make the actual call to the Collection’s fetch method to retrieve the data from the data source. Here, we basically make a call to Google’s stock webservice to retrieve some data on a company called Lockheed Martin.
Finally, in our View’s render method we update each Knot Gauge with the corresponding value passed back from the server call.
Putting It All Together
Here’s the final backbone example end-to-end: