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">

But we need to construct it pragmatically, so we create an emtpy container for the tags.

1<h3>Find by tags</h3>
2<div data-role='controlgroup' id='tag-list'></div>

And the template for one tag entry.

1<div id='templates'>
2  <li class='book-entry'><!-- existing (previous) book entry --></li>
3  <div class='tag-entry'>
4    <label for="tag-dummy">dummy</label>
5    <input type="checkbox" name="tag-dummy" id="tag-dummy">
6  </div>

tags that separated by comma.

 1data.loadTags = function() {
 2  return"tags");
 4data.addTags = function(tagsString) {
 5  var tags = tagsString.split(/\s*,\s*/);
 6  var oldTags ="tags");
 7  var newTags = _.union(oldTags, tags);
 8"tags", newTags);

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.


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();
 6  var tags =;
 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');

Whenever we call renderList(), we render the tags also.


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”.

overlaied image when clicked on thumbnail

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