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>

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;

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.
 4  var app = || ({});
 6  var view = app.view = {}
 8  view.listElement = $('#books');
10  view.bookEntryTemplate = $('#templates').find('.book-entry');
12  view.renderList = function(){
13    view.listElement.empty();
15    for(var i=0,; i<len; i++) {
16      var clone = view.bookEntryTemplate.clone();
18      view.listElement.append(clone);
19    }
21    view.listElement.listview('refresh');
22  }
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.

2'Testing book', '1234567890123');
2'Testing book', '1234567890123');
3  app.view.renderList();

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