Cloning with data

Now time to make it works with the real data. First, we get rid of the hardcoded data in the view template. Then we add some identification to the title and ISBN tags so that we can insert data from JavaScript. Here I used classes but whatever method works as long as you can inject the data to the desired place.

Please note that we do not use ID here because these elements are meant to be cloned while ID should be unique.

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>
1<div id='templates'>
2  <li class='book-entry'>
3    <h1 class='book-title'></h1>
4    <p class='isbn'></p>
5    <p class='ui-li-count'><a href='#' class='delete-btn' data-isbn=''>X Remove</a></p>
6  </li>
7</div>

And when the list item is cloned, we inject the book title and ISBN information to the newly cloned list item.

 1view.renderList = function(){
 2  view.listElement.empty();
 3
 4  for(var i=0, len=app.data.books.length; i<len; i++) {
 5    var clone = view.bookEntryTemplate.clone();
 6
 7    var book = app.data.books[i];
 8
 9    view.listElement.append(clone);
10  }
11
12  view.listElement.listview('refresh');
13}
 1view.renderList = function(){
 2  view.listElement.empty();
 3
 4  for(var i=0, len=app.data.books.length; i<len; i++) {
 5    var clone = view.bookEntryTemplate.clone();
 6
 7    var book = app.data.books[i];
 8
 9    // ↓↓↓↓↓ Added
10    clone.find('.book-title').html(book.title);
11    clone.find('.isbn').html(book.isbn);
12    clone.find('.delete-btn').attr('data-isbn', book.isbn);
13    // -----------------------------
14
15    view.listElement.append(clone);
16  }
17
18  view.listElement.listview('refresh');
19}

What’s next? We’re going to take a look at “Remove book entry”.

overlaied image when clicked on thumbnail

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