jQuery 库中使用的设计模式 [英] Design Patterns used in the jQuery library

查看:17
本文介绍了jQuery 库中使用的设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery 高度关注 DOM,并围绕它提供了很好的抽象.在这样做时,它利用了昨天刚打到我的各种众所周知的设计模式.一个明显的例子是 Decorator 模式.jQuery 对象围绕常规 DOM 对象提供新的和附加的功能.

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.

例如,DOM 有一个原生的 insertBefore 方法,但没有对应的 insertAfter 方法.有各种实现可用来填充这个差距,而 jQuery 就是一个提供这种功能的库:

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(..)

在 jQuery 中还有许多其他大量使用装饰器模式的例子.

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.

把它变成一个社区维基,因为我相信人们喜欢 jQuery 的各种事情都可以追溯到众所周知的设计模式,只是它们通常不以模式名称来指代.这个问题没有一个答案,但对这些模式进行分类将有助于深入了解图书馆本身.

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.

推荐答案

延迟初始化:

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

适配器或包装器

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

立面

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

观察员

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

迭代器

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

策略

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

代理

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

构建器

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

原型

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

蝇量级

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

这篇关于jQuery 库中使用的设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆