Book Image

Backbone.js Blueprints

By : Andrew Burgess
Book Image

Backbone.js Blueprints

By: Andrew Burgess

Overview of this book

<p>Backbone.js is an open source, JavaScript library that helps you to build sophisticated and structured web apps. It's important to have well-organized frontend code for easy maintenance and extendability. With the Backbone framework, you'll be able to build applications that are a breeze to manage.<br /><br />In this book, you will discover how to build seven complete web applications from scratch. You'll learn how to use all the components of the Backbone framework individually, and how to use them together to create fully featured applications. In addition, you'll also learn how Backbone thinks so you can leverage it to write the most efficient frontend JavaScript code.<br /><br />Through this book, you will learn to write good server-side JavaScript to support your frontend applications. This easy-to-follow guide is packed with projects, code, and solid explanations that will give you the confidence to write your own web applications from scratch.</p>
Table of Contents (14 chapters)
Backbone.js Blueprints
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Performing a quick and dirty test


We've actually written enough code at this point to test things out. Head to http://localhost:3000 in your browser and pop open a JavaScript console; I prefer Chrome and the Developer tools but use whatever you want. Now try the following lines:

var posts = new Posts();
posts.length // => 0

We can create a Posts collection instance; as you can see, it's empty by default. We can load the data from the server by running the following line:

posts.fetch();

A collection instance's fetch method will send a GET request to the server (in fact, if your in-browser tools allow you to see a network request, you'll see a GET request to /posts). It will merge the models that it receives from the server with the ones already in the collection. Give a second to get a response and then run the following lines:

posts.length // => 1
var post = posts.get(1);
post.get("title"); // Lorem Ipsum

Every collection instance has a get method; we pass it an ID and it will return the model instance with that ID (note that this is the id field from the database, and not the index number in the collection). Then, each model instance has a get method that we can use to get properties.