jQuery: creating widgets

In this post I will show you how to create a simple HTML widget to be used with the jQuery's html() method. Our widget, called ListWidget, create ordered and unordered lists using an array of values passed as one of its options. This widget can actually be more generalized to encompass a wider variety of HTML elements. The major advantage of this widget-based approach is that you keep your code more compact and organized. Here's the code:

var ListWidget = function(options) {


  options = $.extend({
    content: [],
    type: 'ul'
  }, options);
   
  this.render = function() {
    
     if(!$.isArray(options.content)) {
     
       throw new Error('content must be an array');
       
       return;
     
     }
     
     var newHTML = '<' + options.type + '>';
     var i, len = options.content.length;
     
     for(i = 0; i < len; i += 1) {
     
       newHTML += '<li>' + options.content[i] + '</li>';
     
     
     }
     
     newHTML += '</' + options.type + '>';
     
     return newHTML;
          
     

  }
};

A further improvement to this widget is to check whether the content array is empty or not. In this example I'm assuming that a user will always fill the array with some values, but it might occur a reference error somewhere, so it's better to add this check:

if(options.content.length == 0) {

  throw new Error('content cannot be empty');
  return;

}

As I said earlier, this widget work together with the html() method:

$(function() {

  $('#test').html(function() {
  
    var list = new ListWidget({
      content: ['a', 'b', 'c'],
      type: 'ol'
    });
    
    return list.render(); 
  
  
  }); 

});

Widgets are not plugins. They're not bound to the jQuery's chain nor to its objects. You can use and reuse them in many scenarios.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.