Introduction
Welcome to the "Demonstrating Backbone.js" article series. This article demonstrates how to create a students directory using backbone.js. This article starts with the concept of Backbone.js and various components of it. Previous articles have provided an introduction to views and the implementation of routers and collections. You can get them from the following:
In a previous article we learned how to create an outline of a Students Directory app. Here we will see how to use the generated JSON data in our app.
- Step 1: Now create a .json file using Notepad and copy the generated data to the .json file..
- Step 2 Now add an index.html page and create the UI as in the following:
- <!DOCTYPE html>
- <html>
- <head>
- <title>Student Directory with Backbone.js</title>
- <link href="css/style.css" rel="stylesheet" />
- </head>
- <body>
-
- <div id="heading">
- <h1>Students Directory</h1>
- <div class="tools">
- Search:<br />
- <input type="text" id="searchBox" /><br /><br />
- Filter:
- <div id="filters"></div>
- <div id="count"></div>
- </div>
- <ul id="listing"></ul>
- </div>
-
- <script type="text/template" id="person-template">
- <span class="list-header"><%= firstname %> <%= lastname %> (<%= type %>)</span>
- <div class="details">
- home phone: <%= homephone %><br/>
- email: <a href="mailto:<%= email %>"><%= email %></a>
- </div>
- </script>
-
- <script src="js/Studentdata.json" type="text/javascript"></script>
-
- <script src="js/libraries/jquery-1.10.2.min.js" type="text/javascript"></script>
- <script src="js/libraries/underscore-min.js" type="text/javascript"></script>
- <script src="js/libraries/backbone-min.js" type="text/javascript"></script>
- </body>
- </html>
We will see the following output:
- Step 3 Create a folder named routers and add a router.js file with the following script:
- app = {
-
- models: {},
- views: {},
- collections: {},
- routers: {},
- init: function() {}
-
- }
- Step 4 Now let's create a model. Create a new folder named models in the solution and add a JavaScript file
Now add the following script.
Here we have created the fields in the model as in the JSON file and we have initialized a model. If the parent is not empty, that is a student, otherwise if it is empty then it is a parent. We have called a comparator to sort based on the last name.
- app = app || {};
-
- app.models.Person = Backbone.Model.extend({
- defaults: {
- 'ID': '',
- 'firstname': '',
- 'lastname': '',
- 'homephone': '',
- 'email': '',
- 'parent': ''
- },
-
- initialize: function() {
- var self = this;
- if(this.get('parent') !== '') {
- self.set('type', 'student');
- } else {
- self.set('type', 'parent');
- }
- }
-
- });
-
- app.collections.People = Backbone.Collection.extend({
-
- model: app.models.Person,
-
- comparator: function(person) {
- return person.get('lastname');
- }
-
- });
Summary
In this article we learned how to add the Model and Routers for the Students directory applicaiton.