PageRenderTime 47ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/chapters/05-exercise-2.md

https://github.com/bbt123/backbone-fundamentals
Markdown | 972 lines | 739 code | 233 blank | 0 comment | 0 complexity | 05462f4d1548f9e8eff204dc6d5d1ec4 MD5 | raw file
  1. # Exercise 2: Book Library - Your First RESTful Backbone.js App
  2. While our first application gave us a good taste of how Backbone.js applications are made, most real-world applications will want to communicate with a back-end of some sort. Let's reinforce what we have already learned with another example, but this time we will also create a RESTful API for our application to talk to.
  3. In this exercise we will build a library application for managing digital books using Backbone. For each book we will store the title, author, date of release, and some keywords. We'll also show a picture of the cover.
  4. ##Setting up
  5. First we need to create a folder structure for our project. To keep the front-end and back-end separate, we will create a folder called *site* for our client in the project root. Within it we will create css, img, and js directories.
  6. As with the last example we will split our JavaScript files by their function, so under the js directory create folders named lib, models, collections, and views. Your directory hierarchy should look like this:
  7. ```
  8. site/
  9. css/
  10. img/
  11. js/
  12. collections/
  13. lib/
  14. models/
  15. views/
  16. ```
  17. Download the Backbone, Underscore, and jQuery libraries and copy them to your js/lib folder. We need a placeholder image for the book covers. Save this image to your site/img folder:
  18. ![](img/placeholder.png)
  19. Just like before we need to load all of our dependencies in the site/index.html file:
  20. ```html
  21. <!DOCTYPE html>
  22. <html lang="en">
  23. <head>
  24. <meta charset="UTF-8"/>
  25. <title>Backbone.js Library</title>
  26. <link rel="stylesheet" href="css/screen.css">
  27. </head>
  28. <body>
  29. <script src="js/lib/jquery.min.js"></script>
  30. <script src="js/lib/underscore-min.js"></script>
  31. <script src="js/lib/backbone-min.js"></script>
  32. <script src="js/models/book.js"></script>
  33. <script src="js/collections/library.js"></script>
  34. <script src="js/views/book.js"></script>
  35. <script src="js/views/library.js"></script>
  36. <script src="js/app.js"></script>
  37. </body>
  38. </html>
  39. ```
  40. We should also add in the HTML for the user interface. We'll want a form for adding a new book so add the following immediately inside the `body` element:
  41. ```html
  42. <div id="books">
  43. <form id="addBook" action="#">
  44. <div>
  45. <label for="coverImage">CoverImage: </label><input id="coverImage" type="file" />
  46. <label for="title">Title: </label><input id="title" type="text" />
  47. <label for="author">Author: </label><input id="author" type="text" />
  48. <label for="releaseDate">Release date: </label><input id="releaseDate" type="text" />
  49. <label for="keywords">Keywords: </label><input id="keywords" type="text" />
  50. <button id="add">Add</button>
  51. </div>
  52. </form>
  53. </div>
  54. ```
  55. and we'll need a template for displaying each book which should be placed before the `script` tags:
  56. ```html
  57. <script id="bookTemplate" type="text/template">
  58. <img src="<%= coverImage %>"/>
  59. <ul>
  60. <li><%= title %></li>
  61. <li><%= author %></li>
  62. <li><%= releaseDate %></li>
  63. <li><%= keywords %></li>
  64. </ul>
  65. <button class="delete">Delete</button>
  66. </script>
  67. ```
  68. To see what this will look like with some data in it, go ahead and add a manually filled-in book to the *books* div.
  69. ```html
  70. <div class="bookContainer">
  71. <img src="img/placeholder.png"/>
  72. <ul>
  73. <li>Title</li>
  74. <li>Author</li>
  75. <li>Release Date</li>
  76. <li>Keywords</li>
  77. </ul>
  78. <button class="delete">Delete</button>
  79. </div>
  80. ```
  81. Open this file in a browser and it should look something like this:
  82. ![](img/chapter5-1.png)
  83. Not so great. This is not a CSS tutorial, but we still need to do some formatting. Create a file named screen.css in your site/css folder:
  84. ```css
  85. body {
  86. background-color: #eee;
  87. }
  88. .bookContainer {
  89. outline: 1px solid #aaa;
  90. width: 350px;
  91. height: 130px;
  92. background-color: #fff;
  93. float: left;
  94. margin: 5px;
  95. }
  96. .bookContainer img {
  97. float: left;
  98. margin: 10px;
  99. }
  100. .bookContainer ul {
  101. list-style-type: none;
  102. margin-bottom: 0;
  103. }
  104. .bookContainer button {
  105. float: right;
  106. margin: 10px;
  107. }
  108. #addBook label {
  109. width: 100px;
  110. margin-right: 10px;
  111. text-align: right;
  112. line-height: 25px;
  113. }
  114. #addBook label, #addBook input {
  115. display: block;
  116. margin-bottom: 10px;
  117. float: left;
  118. }
  119. #addBook label[for="title"], #addBook label[for="releaseDate"] {
  120. clear: both;
  121. }
  122. #addBook button {
  123. display: block;
  124. margin: 5px 20px 10px 10px;
  125. float: right;
  126. clear: both;
  127. }
  128. #addBook div {
  129. width: 550px;
  130. }
  131. #addBook div:after {
  132. content: "";
  133. display: block;
  134. height: 0;
  135. visibility: hidden;
  136. clear: both;
  137. font-size: 0;
  138. line-height: 0;
  139. }
  140. ```
  141. Now it looks a bit better:
  142. ![](img/chapter5-2.png)
  143. So this is what we want the final result to look like, but with more books. Go ahead and copy the bookContainer div a few more times if you would like to see what it looks like. Now we are ready to start developing the actual application.
  144. #### Creating the Model, Collection, Views, and App
  145. First, we'll need a model of a book and a collection to hold the list. These are both very simple, with the model only declaring some defaults:
  146. ```javascript
  147. // site/js/models/book.js
  148. var app = app || {};
  149. app.Book = Backbone.Model.extend({
  150. defaults: {
  151. coverImage: 'img/placeholder.png',
  152. title: 'No title',
  153. author: 'Unknown',
  154. releaseDate: 'Unknown',
  155. keywords: 'None'
  156. }
  157. });
  158. ```
  159. ```javascript
  160. // site/js/collections/library.js
  161. var app = app || {};
  162. app.Library = Backbone.Collection.extend({
  163. model: app.Book
  164. });
  165. ```
  166. Next, in order to display books we'll need a view:
  167. ```javascript
  168. // site/js/views/book.js
  169. var app = app || {};
  170. app.BookView = Backbone.View.extend({
  171. tagName: 'div',
  172. className: 'bookContainer',
  173. template: _.template( $( '#bookTemplate' ).html() ),
  174. render: function() {
  175. //this.el is what we defined in tagName. use $el to get access to jQuery html() function
  176. this.$el.html( this.template( this.model.attributes ) );
  177. return this;
  178. }
  179. });
  180. ```
  181. We'll also need a view for the list itself:
  182. ```javascript
  183. // site/js/views/library.js
  184. var app = app || {};
  185. app.LibraryView = Backbone.View.extend({
  186. el: '#books',
  187. initialize: function( initialBooks ) {
  188. this.collection = new app.Library( initialBooks );
  189. this.render();
  190. },
  191. // render library by rendering each book in its collection
  192. render: function() {
  193. this.collection.each(function( item ) {
  194. this.renderBook( item );
  195. }, this );
  196. },
  197. // render a book by creating a BookView and appending the
  198. // element it renders to the library's element
  199. renderBook: function( item ) {
  200. var bookView = new app.BookView({
  201. model: item
  202. });
  203. this.$el.append( bookView.render().el );
  204. }
  205. });
  206. ```
  207. Note that in the initialize function we accept an array of data that we pass to the app.Library constructor. We'll use this to populate our collection with some sample data so that we can see everything is working correctly. Finally, we have the entry point for our code, along with the sample data:
  208. ```javascript
  209. // site/js/app.js
  210. var app = app || {};
  211. $(function() {
  212. var books = [
  213. { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford', releaseDate: '2008', keywords: 'JavaScript Programming' },
  214. { title: 'The Little Book on CoffeeScript', author: 'Alex MacCaw', releaseDate: '2012', keywords: 'CoffeeScript Programming' },
  215. { title: 'Scala for the Impatient', author: 'Cay S. Horstmann', releaseDate: '2012', keywords: 'Scala Programming' },
  216. { title: 'American Psycho', author: 'Bret Easton Ellis', releaseDate: '1991', keywords: 'Novel Splatter' },
  217. { title: 'Eloquent JavaScript', author: 'Marijn Haverbeke', releaseDate: '2011', keywords: 'JavaScript Programming' }
  218. ];
  219. new app.LibraryView( books );
  220. });
  221. ```
  222. Our app just passes the sample data to a new instance of app.LibraryView that it creates. Since the `initialize()` constructor in LibraryView invokes the view's `render()` method, all the books in the library will be displayed. Since we are passing our entry point as a callback to jQuery (in the form of its $ alias), the function will execute when the DOM is ready.
  223. If you view index.html in a browser you should see something like this:
  224. ![](img/chapter5-3.png)
  225. This is a complete Backbone application, though it doesn't yet do anything interesting.
  226. ##Wiring in the interface
  227. Now we'll add some functionality to the useless form at the top and the delete buttons on each book.
  228. ###Adding models
  229. When the user clicks the add button we want to take the data in the form and use it to create a new model. In the LibraryView we need to add an event handler for the click event:
  230. ```javascript
  231. events:{
  232. 'click #add':'addBook'
  233. },
  234. addBook: function( e ) {
  235. e.preventDefault();
  236. var formData = {};
  237. $( '#addBook div' ).children( 'input' ).each( function( i, el ) {
  238. if( $( el ).val() != '' )
  239. {
  240. formData[ el.id ] = $( el ).val();
  241. }
  242. });
  243. this.collection.add( new app.Book( formData ) );
  244. },
  245. ```
  246. We select all the input elements of the form that have a value and iterate over them using jQuery's each. Since we used the same names for ids in our form as the keys on our Book model we can simply store them directly in the formData object. We then create a new Book from the data and add it to the collection. We skip fields without a value so that the defaults will be applied.
  247. Backbone passes an event object as a parameter to the event-handling function. This is useful for us in this case since we don't want the form to actually submit and reload the page. Adding a call to `preventDefault` on the event in the `addBook` function takes care of this for us.
  248. Now we just need to make the view render again when a new model is added. To do this, we put
  249. ```javascript
  250. this.listenTo( this.collection, 'add', this.renderBook );
  251. ```
  252. in the initialize function of LibraryView.
  253. Now you should be ready to take the application for a spin.
  254. ![](img/chapter5-4.png)
  255. You may notice that the file input for the cover image isnt working, but that is left as an exercise to the reader.
  256. ###Removing models
  257. Next, we need to wire up the delete button. Set up the event handler in the BookView:
  258. ```javascript
  259. events: {
  260. 'click .delete': 'deleteBook'
  261. },
  262. deleteBook: function() {
  263. //Delete model
  264. this.model.destroy();
  265. //Delete view
  266. this.remove();
  267. },
  268. ```
  269. You should now be able to add and remove books from the library.
  270. ##Creating the back-end
  271. Now we need to make a small detour and set up a server with a REST api. Since this is a JavaScript book we will use JavaScript to create the server using node.js. If you are more comfortable in setting up a REST server in another language, this is the API you need to conform to:
  272. ```
  273. url HTTP Method Operation
  274. /api/books GET Get an array of all books
  275. /api/books/:id GET Get the book with id of :id
  276. /api/books POST Add a new book and return the book with an id attribute added
  277. /api/books/:id PUT Update the book with id of :id
  278. /api/books/:id DELETE Delete the book with id of :id
  279. ```
  280. The outline for this section looks like this:
  281. * Install node.js, npm, and MongoDB
  282. * Install node modules
  283. * Create a simple web server
  284. * Connect to the database
  285. * Create the REST API
  286. ###Install node.js, npm, and MongoDB
  287. Download and install node.js from nodejs.org. The node package manager (npm) will be installed as well.
  288. Download, install, and run MongoDB from mongodb.org (you need Mongo to be running to store data in a Mongo database). There are detailed installation guides [on the website](http://docs.mongodb.org/manual/installation/).
  289. ###Install node modules
  290. Create a file called `package.json` in the root of your project. It should look like
  291. ```javascript
  292. {
  293. "name": "backbone-library",
  294. "version": "0.0.1",
  295. "description": "A simple library application using Backbone",
  296. "dependencies": {
  297. "express": "~3.1.0",
  298. "path": "~0.4.9",
  299. "mongoose": "~3.5.5"
  300. }
  301. }
  302. ```
  303. Amongst other things, this file tells npm what the dependencies are for our project. On the command line, from the root of your project, type:
  304. ```sh
  305. npm install
  306. ```
  307. You should see npm fetch the dependencies that we listed in our package.json and save them within a folder called node_modules.
  308. Your folder structure should look something like this:
  309. ```
  310. node_modules/
  311. .bin/
  312. express/
  313. mongoose/
  314. path/
  315. site/
  316. css/
  317. img/
  318. js/
  319. index.html
  320. package.json
  321. ```
  322. ###Create a simple web server
  323. Create a file named server.js in the project root containing the following code:
  324. ```javascript
  325. // Module dependencies.
  326. var application_root = __dirname,
  327. express = require( 'express' ), //Web framework
  328. path = require( 'path' ), //Utilities for dealing with file paths
  329. mongoose = require( 'mongoose' ); //MongoDB integration
  330. //Create server
  331. var app = express();
  332. // Configure server
  333. app.configure( function() {
  334. //parses request body and populates request.body
  335. app.use( express.bodyParser() );
  336. //checks request.body for HTTP method overrides
  337. app.use( express.methodOverride() );
  338. //perform route lookup based on url and HTTP method
  339. app.use( app.router );
  340. //Where to serve static content
  341. app.use( express.static( path.join( application_root, 'site') ) );
  342. //Show all errors in development
  343. app.use( express.errorHandler({ dumpExceptions: true, showStack: true }));
  344. });
  345. //Start server
  346. var port = 4711;
  347. app.listen( port, function() {
  348. console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
  349. });
  350. ```
  351. We start off by loading the modules required for this project: Express for creating the HTTP server, Path for dealing with file paths, and mongoose for connecting with the database. We then create an Express server and configure it using an anonymous function. This is a pretty standard configuration and for our application we dont actually need the methodOverride part. It is used for issuing PUT and DELETE HTTP requests directly from a form, since forms normally only support GET and POST. Finally, we start the server by running the listen function. The port number used, in this case 4711, could be any free port on your system. I simply used 4711 since it is unlikely to have been used by anything else. We are now ready to run our first server:
  352. ```javascript
  353. node server.js
  354. ```
  355. If you open a browser on http://localhost:4711 you should see something like this:
  356. ![](img/chapter5-5.png)
  357. This is where we left off in Part 2, but we are now running on a server instead of directly from the files. Great job! We can now start defining routes (URLs) that the server should react to. This will be our REST API. Routes are defined by using app followed by one of the HTTP verbs get, put, post, and delete, which corresponds to Create, Read, Update and Delete. Let us go back to server.js and define a simple route:
  358. ```javascript
  359. // Routes
  360. app.get( '/api', function( request, response ) {
  361. response.send( 'Library API is running' );
  362. });
  363. ```
  364. The get function takes a URL as the first parameter and a function as the second. The function will be called with request and response objects. Now you can restart node and go to our specified URL:
  365. ![](img/chapter5-6.png)
  366. ###Connect to the database
  367. Fantastic. Now, since we want to store our data in MongoDB, we need to define a schema. Add this to server.js:
  368. ```javascript
  369. //Connect to database
  370. mongoose.connect( 'mongodb://localhost/library_database' );
  371. //Schemas
  372. var Book = new mongoose.Schema({
  373. title: String,
  374. author: String,
  375. releaseDate: Date
  376. });
  377. //Models
  378. var BookModel = mongoose.model( 'Book', Book );
  379. ```
  380. As you can see, schema definitions are quite straight forward. They can be more advanced, but this will do for us. I also extracted a model (BookModel) from Mongo. This is what we will be working with. Next up, we define a GET operation for the REST API that will return all books:
  381. ```javascript
  382. //Get a list of all books
  383. app.get( '/api/books', function( request, response ) {
  384. return BookModel.find( function( err, books ) {
  385. if( !err ) {
  386. return response.send( books );
  387. } else {
  388. return console.log( err );
  389. }
  390. });
  391. });
  392. ```
  393. The find function of Model is defined like this: `function find (conditions, fields, options, callback)` but since we want a function that returns all books we only need the callback parameter. The callback will be called with an error object and an array of found objects. If there was no error we return the array of objects to the client using the `send` function of the response object, otherwise we log the error to the console.
  394. To test our API we need to do a little typing in a JavaScript console. Restart node and go to localhost:4711 in your browser. Open up the JavaScript console. If you are using Google Chrome, go to View->Developer->JavaScript Console. If you are using Firefox, install Firebug and go to View->Firebug. Most other browsers will have a similar console. In the console type the following:
  395. ```javascript
  396. jQuery.get( '/api/books/', function( data, textStatus, jqXHR ) {
  397. console.log( 'Get response:' );
  398. console.dir( data );
  399. console.log( textStatus );
  400. console.dir( jqXHR );
  401. });
  402. ```
  403. and press enter and you should get something like this:
  404. ![](img/chapter5-7.png)
  405. Here I used jQuery to make the call to our REST API, since it was already loaded on the page. The returned array is obviously empty, since we have not put anything into the database yet. Let's go and create a POST route that enables adding new items in server.js:
  406. ```javascript
  407. //Insert a new book
  408. app.post( '/api/books', function( request, response ) {
  409. var book = new BookModel({
  410. title: request.body.title,
  411. author: request.body.author,
  412. releaseDate: request.body.releaseDate
  413. });
  414. return book.save( function( err ) {
  415. if( !err ) {
  416. console.log( 'created' );
  417. return response.send( book );
  418. } else {
  419. console.log( err );
  420. }
  421. });
  422. });
  423. ```
  424. We start by creating a new BookModel, passing an object with title, author, and releaseDate attributes. The data are collected from request.body. This means that anyone calling this operation in the API needs to supply a JSON object containing the title, author, and releaseDate attributes. Actually, the caller can omit any or all attributes since we have not made any of them mandatory.
  425. We then call the save function on the BookModel passing in a callback in the same way as with the previous get route. Finally, we return the saved BookModel. The reason we return the BookModel and not just success or similar string is that when the BookModel is saved it will get an _id attribute from MongoDB, which the client needs when updating or deleting a specific book. Let's try it out again. Restart node and go back to the console and type:
  426. ```javascript
  427. jQuery.post( '/api/books', {
  428. 'title': 'JavaScript the good parts',
  429. 'author': 'Douglas Crockford',
  430. 'releaseDate': new Date( 2008, 4, 1 ).getTime()
  431. }, function(data, textStatus, jqXHR) {
  432. console.log( 'Post response:' );
  433. console.dir( data );
  434. console.log( textStatus );
  435. console.dir( jqXHR );
  436. });
  437. ```
  438. ..and then
  439. ```javascript
  440. jQuery.get( '/api/books/', function( data, textStatus, jqXHR ) {
  441. console.log( 'Get response:' );
  442. console.dir( data );
  443. console.log( textStatus );
  444. console.dir( jqXHR );
  445. });
  446. ```
  447. You should now get a one-element array back from our server. You may wonder about this line:
  448. ```javascript
  449. 'releaseDate': new Date(2008, 4, 1).getTime()
  450. ```
  451. MongoDB expects dates in UNIX time format (milliseconds from the start of Jan 1st 1970 UTC), so we have to convert dates before posting. The object we get back however, contains a JavaScript Date object. Also note the _id attribute of the returned object.
  452. ![](img/chapter5-8.png)
  453. Let's move on to creating a GET request that retrieves a single book in server.js:
  454. ```javascript
  455. //Get a single book by id
  456. app.get( '/api/books/:id', function( request, response ) {
  457. return BookModel.findById( request.params.id, function( err, book ) {
  458. if( !err ) {
  459. return response.send( book );
  460. } else {
  461. return console.log( err );
  462. }
  463. });
  464. });
  465. ```
  466. Here we use colon notation (:id) to tell Express that this part of the route is dynamic. We also use the `findById` function on BookModel to get a single result. If you restart node, you can get a single book by adding the id previously returned to the URL like this:
  467. ```javascript
  468. jQuery.get( '/api/books/4f95a8cb1baa9b8a1b000006', function( data, textStatus, jqXHR ) {
  469. console.log( 'Get response:' );
  470. console.dir( data );
  471. console.log( textStatus );
  472. console.dir( jqXHR );
  473. });
  474. ```
  475. Let's create the PUT (update) function next:
  476. ```javascript
  477. //Update a book
  478. app.put( '/api/books/:id', function( request, response ) {
  479. console.log( 'Updating book ' + request.body.title );
  480. return BookModel.findById( request.params.id, function( err, book ) {
  481. book.title = request.body.title;
  482. book.author = request.body.author;
  483. book.releaseDate = request.body.releaseDate;
  484. return book.save( function( err ) {
  485. if( !err ) {
  486. console.log( 'book updated' );
  487. return response.send( book );
  488. } else {
  489. console.log( err );
  490. }
  491. });
  492. });
  493. });
  494. ```
  495. This is a little larger than previous ones, but is also pretty straight forward we find a book by id, update its properties, save it, and send it back to the client.
  496. To test this we need to use the more general jQuery ajax function. Again, in these examples you will need to replace the id property with one that matches an item in your own database:
  497. ```javascript
  498. jQuery.ajax({
  499. url: '/api/books/4f95a8cb1baa9b8a1b000006',
  500. type: 'PUT',
  501. data: {
  502. 'title': 'JavaScript The good parts',
  503. 'author': 'The Legendary Douglas Crockford',
  504. 'releaseDate': new Date( 2008, 4, 1 ).getTime()
  505. },
  506. success: function( data, textStatus, jqXHR ) {
  507. console.log( 'Post response:' );
  508. console.dir( data );
  509. console.log( textStatus );
  510. console.dir( jqXHR );
  511. }
  512. });
  513. ```
  514. Finally we create the delete route:
  515. ```javascript
  516. //Delete a book
  517. app.delete( '/api/books/:id', function( request, response ) {
  518. console.log( 'Deleting book with id: ' + request.params.id );
  519. return BookModel.findById( request.params.id, function( err, book ) {
  520. return book.remove( function( err ) {
  521. if( !err ) {
  522. console.log( 'Book removed' );
  523. return response.send( '' );
  524. } else {
  525. console.log( err );
  526. }
  527. });
  528. });
  529. });
  530. ```
  531. and try it out:
  532. ```javascript
  533. jQuery.ajax({
  534. url: '/api/books/4f95a5251baa9b8a1b000001',
  535. type: 'DELETE',
  536. success: function( data, textStatus, jqXHR ) {
  537. console.log( 'Post response:' );
  538. console.dir( data );
  539. console.log( textStatus );
  540. console.dir( jqXHR );
  541. }
  542. });
  543. ```
  544. So now our REST API is complete we have support for all four HTTP verbs. What's next? Well, until now I have left out the keywords part of our books. This is a bit more complicated since a book could have several keywords and we don’t want to represent them as a string, but rather an array of strings. To do that we need another schema. Add a Keywords schema right above our Book schema:
  545. ```javascript
  546. //Schemas
  547. var Keywords = new mongoose.Schema({
  548. keyword: String
  549. });
  550. ```
  551. To add a sub schema to an existing schema we use brackets notation like so:
  552. ```javascript
  553. var Book = new mongoose.Schema({
  554. title: String,
  555. author: String,
  556. releaseDate: Date,
  557. keywords: [ Keywords ] // NEW
  558. });
  559. ```
  560. Also update POST and PUT:
  561. ```javascript
  562. //Insert a new book
  563. app.post( '/api/books', function( request, response ) {
  564. var book = new BookModel({
  565. title: request.body.title,
  566. author: request.body.author,
  567. releaseDate: request.body.releaseDate,
  568. keywords: request.body.keywords // NEW
  569. });
  570. book.save( function( err ) {
  571. if( !err ) {
  572. console.log( 'created' );
  573. return response.send( book );
  574. } else {
  575. return console.log( err );
  576. }
  577. });
  578. });
  579. //Update a book
  580. app.put( '/api/books/:id', function( request, response ) {
  581. console.log( 'Updating book ' + request.body.title );
  582. return BookModel.findById( request.params.id, function( err, book ) {
  583. book.title = request.body.title;
  584. book.author = request.body.author;
  585. book.releaseDate = request.body.releaseDate;
  586. book.keywords = request.body.keywords; // NEW
  587. return book.save( function( err ) {
  588. if( !err ) {
  589. console.log( 'book updated' );
  590. } else {
  591. console.log( err );
  592. }
  593. return response.send( book );
  594. });
  595. });
  596. });
  597. ```
  598. There we are, that should be all we need, now we can try it out in the console:
  599. ```javascript
  600. jQuery.post( '/api/books', {
  601. 'title': 'Secrets of the JavaScript Ninja',
  602. 'author': 'John Resig',
  603. 'releaseDate': new Date( 2008, 3, 12 ).getTime(),
  604. 'keywords':[
  605. { 'keyword': 'JavaScript' },
  606. { 'keyword': 'Reference' }
  607. ]
  608. }, function( data, textStatus, jqXHR ) {
  609. console.log( 'Post response:' );
  610. console.dir( data );
  611. console.log( textStatus );
  612. console.dir( jqXHR );
  613. });
  614. ```
  615. You now have a fully functional REST server that we can hook into from our front-end.
  616. ##Talking to the server
  617. In this part we will cover connecting our Backbone application to the server through the REST API.
  618. As we mentioned in chapter 3 *Backbone Basics*, we can retrieve models from a server using `collection.fetch()` by setting `collection.url` to be the URL of the API endpoint. Let's update the Library collection to do that now:
  619. ```javascript
  620. var app = app || {};
  621. app.Library = Backbone.Collection.extend({
  622. model: app.Book,
  623. url: '/api/books' // NEW
  624. });
  625. ```
  626. This results in the default implementation of Backbone.sync assuming that the API looks like this:
  627. ```
  628. url HTTP Method Operation
  629. /api/books GET Get an array of all books
  630. /api/books/:id GET Get the book with id of :id
  631. /api/books POST Add a new book and return the book with an id attribute added
  632. /api/books/:id PUT Update the book with id of :id
  633. /api/books/:id DELETE Delete the book with id of :id
  634. ```
  635. To have our application retrieve the Book models from the server on page load we need to update the LibraryView. The Backbone documentation recommends inserting all models when the page is generated on the server side, rather than fetching them from the client side once the page is loaded. Since this chapter is trying to give you a more complete picture of how to communicate with a server, we will go ahead and ignore that recommendation. Go to the LibraryView declaration and update the initialize function as follows:
  636. ```javascript
  637. initialize: function() {
  638. this.collection = new app.Library();
  639. this.collection.fetch({reset: true}); // NEW
  640. this.render();
  641. this.listenTo( this.collection, 'add', this.renderBook );
  642. this.listenTo( this.collection, 'reset', this.render ); // NEW
  643. },
  644. ```
  645. Now that we are populating our Library from the database using `this.collection.fetch()`, the `initialize()` function no longer takes a set of sample data as an argument and doesn't pass anything to the app.Library constructor. You can now remove the sample data from site/js/app.js, which should reduce it to a single statement which creates the LibraryView:
  646. ```javascript
  647. // site/js/app.js
  648. var app = app || {};
  649. $(function() {
  650. new app.LibraryView();
  651. });
  652. ```
  653. We have also added a listener on the reset event. We need to do this since the models are fetched asynchronously after the page is rendered. When the fetch completes, Backbone fires the reset event, as requested by the `reset: true` option, and our listener re-renders the view. If you reload the page now you should see all books that are stored on the server:
  654. ![](img/chapter5-9.png)
  655. As you can see the date and keywords look a bit weird. The date delivered from the server is converted into a JavaScript Date object and when applied to the underscore template it will use the toString() function to display it. There isnt very good support for formatting dates in JavaScript so we will use the dateFormat jQuery plugin to fix this. Go ahead and download it from [here](http://github.com/phstc/jquery-dateFormat) and put it in your site/js/lib folder. Update the book template so that the date is displayed with:
  656. ```html
  657. <li><%= $.format.date( new Date( releaseDate ), 'MMMM yyyy' ) %></li>
  658. ```
  659. and add a script element for the plugin
  660. ```html
  661. <script src="js/lib/jquery-dateFormat-1.0.js"></script>
  662. ```
  663. Now the date on the page should look a bit better. How about the keywords? Since we are receiving the keywords in an array we need to execute some code that generates a string of separated keywords. To do that we can omit the equals character in the template tag which will let us execute code that doesnt display anything:
  664. ```html
  665. <li><% _.each( keywords, function( keyobj ) {%> <%= keyobj.keyword %><% } ); %></li>
  666. ```
  667. Here I iterate over the keywords array using the Underscore `each` function and print out every single keyword. Note that I display the keyword using the <%= tag. This will display the keywords with spaces between them.
  668. Reloading the page again should look quite decent:
  669. ![](img/chapter5-10.png)
  670. Now go ahead and delete a book and then reload the page: Tadaa! the deleted book is back! Not cool, why is this? This happens because when we get the BookModels from the server they have an _id attribute (notice the underscore), but Backbone expects an id attribute (no underscore). Since no id attribute is present, Backbone sees this model as new and deleting a new model doesnt need any synchronization.
  671. To fix this we can use the parse function of Backbone.Model. The parse function lets you edit the server response before it is passed to the Model constructor. Add a parse method to the Book model:
  672. ```javascript
  673. parse: function( response ) {
  674. response.id = response._id;
  675. return response;
  676. }
  677. ```
  678. Simply copy the value of _id to the needed id attribute. If you reload the page you will see that models are actually deleted on the server when you press the delete button.
  679. Another, simpler way of making Backbone recognize _id as its unique identifier is to set the idAttribute of the model to _id.
  680. If you now try to add a new book using the form youll notice that it is a similar story to delete models won't get persisted on the server. This is because Backbone.Collection.add doesn’t automatically sync, but it is easy to fix. In the LibraryView we find in `views/library.js` change the line reading:
  681. ```javascript
  682. this.collection.add( new Book( formData ) );
  683. ```
  684. to:
  685. ```javascript
  686. this.collection.create( formData );
  687. ```
  688. Now newly created books will get persisted. Actually, they probably won't if you enter a date. The server expects a date in UNIX timestamp format (milliseconds since Jan 1, 1970). Also, any keywords you enter won't be stored since the server expects an array of objects with the attribute keyword.
  689. We'll start by fixing the date issue. We don’t really want the users to manually enter a date in a specific format, so we’ll use the standard datepicker from jQuery UI. Go ahead and create a custom jQuery UI download containing datepicker from [here](http://jqueryui.com/download/). Add the css theme to site/css/ and the JavaScript to site/js/lib. Link to them in index.html:
  690. ```html
  691. <link rel="stylesheet" href="css/cupertino/jquery-ui-1.10.0.custom.css">
  692. ```
  693. "cupertino" is the name of the style I chose when downloading jQuery UI.
  694. The JavaScript file must be loaded after jQuery.
  695. ```html
  696. <script src="js/lib/jquery.min.js"></script>
  697. <script src="js/lib/jquery-ui-1.10.0.custom.min.js"></script>
  698. ```
  699. Now in app.js, bind a datepicker to our releaseDate field:
  700. ```javascript
  701. var app = app || {};
  702. $(function() {
  703. $( '#releaseDate' ).datepicker();
  704. new app.LibraryView();
  705. });
  706. ```
  707. You should now be able to pick a date when clicking in the releaseDate field:
  708. ![](img/chapter5-11.png)
  709. Finally, we have to make sure that the form input is properly transformed into our storage format. Change the addBook function in LibraryView to:
  710. ```javascript
  711. addBook: function( e ) {
  712. e.preventDefault();
  713. var formData = {};
  714. $( '#addBook div' ).children( 'input' ).each( function( i, el ) {
  715. if( $( el ).val() != '' )
  716. {
  717. if( el.id === 'keywords' ) {
  718. formData[ el.id ] = [];
  719. _.each( $( el ).val().split( ' ' ), function( keyword ) {
  720. formData[ el.id ].push({ 'keyword': keyword });
  721. });
  722. } else if( el.id === 'releaseDate' ) {
  723. formData[ el.id ] = $( '#releaseDate' ).datepicker( 'getDate' ).getTime();
  724. } else {
  725. formData[ el.id ] = $( el ).val();
  726. }
  727. }
  728. // Clear input field value
  729. $( el ).val('');
  730. });
  731. this.collection.create( formData );
  732. },
  733. ```
  734. Our change adds two checks to the form input fields. First, we're checking if the current element is the keywords input field, in which case we're splitting the string on each space and creating an array of keyword objects.
  735. Then we're checking if the current element is the releaseDate input field, in which case we're calling `datePicker(“getDate”)` which returns a Date object. We then use the `getTime` function on that to get the time in milliseconds.
  736. Now you should be able to add new books with both a release date and keywords!
  737. ![](img/chapter5-12.png)
  738. ### Summary
  739. In this chapter we made our application persistent by binding it to a server using a REST API. We also looked at some problems that might occur when serializing and deserializing data and their solutions. We looked at the dateFormat and the datepicker jQuery plugins and how to do some more advanced things in our Underscore templates. The code is available [here](https://github.com/addyosmani/backbone-fundamentals/tree/gh-pages/practicals/exercise-2).