HTML5 Cheatsheet Example – Moving data from HTML to Javascript

It is not easy to maintain the data by having all of them listing directly in HTML. In this step, we are going to move the data from HTML to Javascript.

For the HTML, we make the UL list view empty in the HTML because we will add list item to this list via script.

1<ul data-role='listview' id='tags'></ul>

And then the core of this part – Model.

 1;(function(){
 2  var app = this.app || (this.app={});
 3
 4  // Tag class
 5  var Tag = (function() {
 6    /*
 7    name - string, tag name
 8    explain - string, one sentence description
 9    html4 - bool, available in html4
10    html5 - bool, not obsoleted in html5
11    */
12    function Tag(name, explain, html4, html5) {
13      this.name = name;
14      this.explain = explain != null ? explain : '';
15      this.html4 = html4 != null ? html4 : 'true';
16      this.html5 = html5 != null ? html5 : 'true';
17    }
18
19    Tag.prototype.toString = function() {
20      return "&lt;" + this.name + "&gt;";
21    }
22
23    return Tag;
24  })(); // end of Tag class
25
26  // the Tag data
27
28  var tags = app.tags = [];
29
30  tags.push(new Tag('br', 'inserts a single line break'));
31  tags.push(new Tag('a', 'defines a hyperlink'));
32  tags.push(new Tag('abbr', 'defines an abbreviation'));
33  /* ... the rest of tags ...  */
34  tags.push(new Tag('video', 'defines a video', false, true));
35
36}).call(this);

And the View to render the given data into the list item.

 1;(function($){
 2  var app = this.app || (this.app={});
 3
 4  app.view = {};
 5
 6  app.view.render = function() {
 7    $('#tags').empty();
 8
 9    //append li to the ul#tags
10    for (var i=0, len=app.tags.length; i<len; i++) {
11      tag = app.tags[i];
12      $('#tags').append("<li>" + tag + "</li>");
13    }
14
15    // refresh the tags listview programatically.
16    $('#tags').listview('refresh');
17  };
18
19}).call(this, jQuery);

From the jQuery doc:

If you add items to a listview, you'll need to call the refresh() method on it to update the styles and create any nested lists that are added. Note that the refresh() method only affects new nodes appended to a list. This is done for performance reasons.

1$('#tags').listview('refresh');

And the controller part is as easy as just calling the view to render the data.

1;(function($){
2
3  // Entry point
4  $(function(){
5    app.view.render();
6  });
7
8}).call(this, jQuery);

Another way to set default value is to make use of the || opreation.

1function Tag(name, explain, html4, html5) {
2  this.name = name;
3  this.explain = explain || '';
4  this.html4 = html4 || 'true';
5  this.html5 = html5 || 'true';
6}

What’s next? We’re going to take a look at “HTML5 Cheatsheet Example – Showing more detail”.

overlaied image when clicked on thumbnail

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