Table of Content
Listing all the tags
New we will treating the tags as data and put into the tags list.
The first thing is to list all tags. It is like listing the books. The tags are going to be clickable by checkbox. We can use controlgroup
to group a list of itmes and make them look like a inset list view.
The target HTML is like the following:
1<div data-role='controlgroup' id='tag-list'> 2 <label for="tag-name1">name1</label> 3 <input type="checkbox" name="tag-name1" id="tag-name1"> 4 <label for="tag-name2">name2</label> 5 <input type="checkbox" name="tag-name2" id="tag-name2"> 6 <label for="tag-name3">name3</label> 7 <input type="checkbox" name="tag-name3" id="tag-name3"> 8</div>
But we need to construct it pragmatically, so we create an emtpy container for the tags.
And the template for one tag entry.
tags that separated by comma.
Normally, we use split(',')
to split a comma-separated string into array. Here we use a regular expression so the split will remove all whitespaces around the comma.
1.split(/\s*,\s*/);
Concern about duplicated tags? _.union
got it covered. It unions the given collections and make sure every item is unique.
Then comes the view logic to render the tag checkboxes into the tags container.
1view.tagList = $('#tag-list'); 2view.tagEntryTemplate = $('#templates').find('.tag-entry'); 3view.renderTags = function() { 4 view.tagList.controlgroup('container').empty(); 5 6 var tags = app.data.loadTags(); 7 8 for(var i=0, len=tags.length; i<len; i++) { 9 var tag = tags[i]; 10 var clone = view.tagEntryTemplate.clone(); 11 var id = 'tag-' + tag; 12 clone.find('label').attr('for', id).html(tag); 13 clone.find('input[type="checkbox"]').attr('name', id).attr('id', id).attr('value', tag); 14 view.tagList.controlgroup('container').append(clone.html()); 15 } 16 $('input[type="checkbox"]').checkboxradio().checkboxradio("refresh"); 17 view.tagList.controlgroup('refresh'); 18}
Whenever we call renderList()
, we render the tags also.
1app.view.renderTags();
Note: If we need to append elements into a control group widget, we want to append it to its container instead of that element directly. This is done by using $(element).controlgroup('container')
.
What’s next? We’re going to take a look at “Know which checkboxes are checked”.