jquery中的设计模式(一)

来源:互联网 发布:windows to go 教程 编辑:程序博客网 时间:2024/05/23 12:45

 Composite(组合)模式

composite模式描述了一组对象,可以使用与处理对象的单个实例同样的方式来进行处理。

这样能使我们能够以统一的方式处理单个对象或者组合。在jQuery中,把方法应用于元素或元素集合时,可以使用统一的方式来处理它们,因为这两种选择都会返回jQuery对象。

例:

    $("#test").addClass(".red");    $(".test").addClass(".red");
可以向单一的元素添或者一组具有test类的元素添加red类,而无需额外的工作。

jQuery源码:

addClass: function( value ) {var classes, elem, cur, clazz, j, finalValue,proceed = typeof value === "string" && value,i = 0,len = this.length;if ( jQuery.isFunction( value ) ) {return this.each(function( j ) {jQuery( this ).addClass( value.call( this, j, this.className ) );});}if ( proceed ) {// The disjunction here is for better compressibility (see removeClass)classes = ( value || "" ).match( rnotwhite ) || [];for ( ; i < len; i++ ) {elem = this[ i ];cur = elem.nodeType === 1 && ( elem.className ?( " " + elem.className + " " ).replace( rclass, " " ) :" ");if ( cur ) {j = 0;while ( (clazz = classes[j++]) ) {if ( cur.indexOf( " " + clazz + " " ) < 0 ) {cur += clazz + " ";}}// only assign if different to avoid unneeded rendering.finalValue = jQuery.trim( cur );if ( elem.className !== finalValue ) {elem.className = finalValue;}}}}return this;}


Adapter(适配器)模式

Adapter模式将对象或类的接口转变为与特定的系统兼容的接口。

jQuery中的适配器:jQuery.fn.css()方法。它不仅有助于标准化接口,以展示样式如何应用于多种浏览器,使我们能轻松的使用简单的语法适配浏览器在后台实际支持的语法。


Facade(外观)模式


Facade 模式为更大的代码体提供了一个更简单的接口。

我们经常在jQuery中发现Facade,它使开发人员能够方便的访问实现,以处理DOM操作、动画以及有趣的Ajax。


下面是jQuery的$.ajax()外观:

$.get(url,data,callback,dataType);

$,post(url,data,callback,dataType);


这些在后头进行转变:

$.ajax({    type:"post",    url:url,    data:data,    dataType:dataType}).done(callback);

更有趣的是,上面的外观实际上是自身功能的外观,在后台隐藏大量的复杂性。

Observer(观察者)模式

jQuery核心具有对Publish/Subscribe 系统的内置支持,它被称为自定义事件。


jQuery早期版本中,使用jquery.bind()  (subscribe)、jQuery.trigger() (publish) 和jQuery.unbind() (unsubscribe)可以访问这些自定义事件,但在新版本中,可以使用JQuery.on()、jQuery.trigger()、jQuery.off()来实现这样目的。

    //等价于subscribe(topicName,callback)$(document).on("topicName",function(){    //do something});    //等价于publish(topicName)    $(document).trigger("topicName");    //等价于unsubscribe(topicName)    $(document).off("topicName");


1 0
原创粉丝点击