Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

jQuery is highly focused on the DOM and provides a nice abstraction around it. In doing so, it makes use of various well known design patterns which just hit me yesterday. One obvious example would be the Decorator pattern. The jQuery object provides new and additional functionality around a regular DOM object.

For example, the DOM has a native insertBefore method but there is no corresponding insertAfter method. There are various implementations available to fill this gap, and jQuery is one such library that provides this functionality:

$(selector).after(..)
$(selector).insertAfter(..)

There are many other examples of the Decorator pattern being heavily used in jQuery.

What other examples, big or small, of design patterns have you noticed that are part of the library itself? Also, please provide an example of the usage of the pattern.

Making this a community wiki as I believe that various things people love about jQuery can be traced back to well known design patterns, just that they are not commonly referred to by the pattern's name. There is no one answer to this question, but cataloging these patterns will provide a useful insight into the library itself.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
196 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...