Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

javascript - Design Patterns used in the jQuery library

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...