jQuery: extending functions

Function parameters have always been a weak point in JavaScript because of the very lenient way of handling them by most JavaScript interpreters. A solution is to use an object literal to handle them. Since jQuery provides the $.extend utility function, why don't we use the same approach used in plugin development to handle function parameters? This is a neat way to extend a function. For example:

function addContent(params) {

  params = $.extend({
    element: null,
    content: ''
  }, params);
  
  var origContent = params.element.html();
  
  return params.element.html(origContent + params.content);


}

This function is similar to the function used to create a plugin, but with a major advantage: it doesn't pollute the global jQuery namespace and can be actually applied to a wide variety of elements. Example:

$(document).ready(function() {


  $('#test li ').each(function() {
  
    var $li = $(this);
    
    addContent({element: $li, content: '<p>Test</p>'});
  
  
  });


});

Further, in this way we can also handle events in a more concise way by attaching a function to an event handler without using an anonymous function. You can see the demo below.

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.