Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design Patterns used in the jQuery library

People also ask

Are design patterns used in JavaScript?

JavaScript modules are the most prevalently used design patterns for keeping particular pieces of code independent of other components. This provides loose coupling to support well-structured code. For those that are familiar with object-oriented languages, modules are JavaScript “classes”.


Lazy Initialization:

$(document).ready(function(){
    $('div.app').myPlugin();
});

Adapter or wrapper

$('div').css({
    opacity: .1 // opacity in modern browsers, filter in IE.
});

Facade

// higher level interfaces (facades) for $.ajax();
$.getJSON();
$.get();
$.getScript();
$.post();

Observer

// jQuery utilizes it's own event system implementation on top of DOM events.
$('div').click(function(){})
$('div').trigger('click', function(){})

Iterator

$.each(function(){});
$('div').each(function(){});

Strategy

$('div').toggle(function(){}, function(){});

Proxy

$.proxy(function(){}, obj); // =oP

Builder

$('<div class="hello">world</div>');

Prototype

// this feels like cheating...
$.fn.plugin = function(){}
$('div').plugin();

Flyweight

// CONFIG is shared
$.fn.plugin = function(CONFIG){
     CONFIG = $.extend({
         content: 'Hello world!'
     }, CONFIG);
     this.html(CONFIG.content);
}

The Composite pattern is also very commonly used in jQuery. Having worked with other libraries, I can see how this pattern is not so obvious as it looks at first sight. The pattern basically says that,

a group of objects are to be treated in the same way as a single instance of an object.

For example, when dealing with a single DOM element or a group of DOM elements, both can be treated in a uniform manner.

$('#someDiv').addClass('green'); // a single DOM element

$('div').addClass('green');      // a collection of DOM elements

How about the Singleton/Module pattern, as discussed in this article about YUI: http://yuiblog.com/blog/2007/06/12/module-pattern/

I believe jQuery uses this pattern in its core, as well as encouraging plug-in developers to use the pattern. Using this pattern is a handy and efficient way of keeping the global namespace clear of clutter, which is further useful by assisting developers in writing clean, encapsulated code.


In the eyes of functional programming, jQuery is a Monad. A Monad is a structure that passes an object to an action, returns the modified object and passes it on to the next action. Like an assembly line.

The Wikipedia article covers the definition very well.