Table of Content
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.
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.
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.
What’s next? We’re going to take a look at “Cloning with data”.