View for adding book

Last time in list view, we construct the HTML right inside the JavaScript logic. We could improve it by moving the HTML code to HTML file. That’s what we are going to do in this example.

We have the data for each book in the model. For the view, we will have multiple list item to represent the book entries. We will use the template approach which put the HTML of the book entry in the HTML file and the JavaScript clone that HTML into the target list.

1<div id='templates'>
2  <li class='book-entry'>
3    <h1>JavaScript: The good parts</h1>
4    <p>1234567890123</p>
5    <p class='ui-li-count'><a href='#' class='delete-btn' data-isbn='1234567890'>X Remove</a></p>
6  </li>
7</div>

The #templates element are used for JavaScript to clone elements. We don’t want to display it to our users. We will hide it with the display:none style.

1#templates {
2  display: none;
3}

The view first cache the listElement and bookEntryTemplate element.

Then in the renderList function, we loop the model data and create a list item for each book. The list item is a clone from the template and then added to the target book list.

Please note that we haven’t deal with the data content yet. The data in the list item view is hardcoded and doesn’t match the model yet.

 1// View
 2// Anything that belongs to interface.
 3;(function($){
 4  var app = this.app || (this.app={});
 5
 6  var view = app.view = {}
 7
 8  view.listElement = $('#books');
 9
10  view.bookEntryTemplate = $('#templates').find('.book-entry');
11
12  view.renderList = function(){
13    view.listElement.empty();
14
15    for(var i=0, len=app.data.books.length; i<len; i++) {
16      var clone = view.bookEntryTemplate.clone();
17
18      view.listElement.append(clone);
19    }
20
21    view.listElement.listview('refresh');
22  }
23
24}).call(this, jQuery);

Please note that using $('#templates').find('.book-entry') is faster than $('#templates .book-entry') in jQuery. See Optimize Selectors for detail.

Now whenever the user add a book to the model, we re-render the book list.

1$('#add-book-btn').click(function(){
2  app.data.addBook('Testing book', '1234567890123');
3});
1$('#add-book-btn').click(function(){
2  app.data.addBook('Testing book', '1234567890123');
3  app.view.renderList();
4});

What’s next? We’re going to take a look at “Cloning with data”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content