Design Patterns used in the jQuery library

后端 未结 4 2000
臣服心动
臣服心动 2020-12-07 07:10

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. O

4条回答
  •  盖世英雄少女心
    2020-12-07 07:19

    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

    $('
    world
    ');

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

提交回复
热议问题