RSS

《jQuery in Action》 in Action - Chapter 7

Labels: ,

Extending jQuery with custom plugins


扩转jQuery的两种形式: 1.在$(jQuery的别名)上直接定义工具方法 2.创建新的操作jQuery结果集(wrapped set)的方法,也可以教程jQuery命令


jQuery推荐的文件命名方式: jquery.yourid.js


扩展jQuery时确保$符号的方法(第六章也介绍过,不解释):



(function($){
$.say = function(what) { alert('I say '+what); }//形式1 一个工具方法的定义
})(jQuery);


jQuery推荐的处理函数参数的方式: 尽可能少的使用参数,如果需要比较多的参数,使用options hash来处理,complex(valueA, {p7: valueB}); 要比 complex(valueA,null,null,null,null,null,valueB);的形式强上不少吧。在我们自己要书写的扩展方法中,用下面的代码就可以很容易的实现options hash,如果你之前接触过prototype.js,一定对这种ruby风格的写法很熟悉了,这样的定义方法简捷、鲁棒、调用方便:


function complex(p1,options) {
 var settings = $.extend({
  option1: defaultValue1,
  option2: defaultValue2,
  option3: defaultValue3,
  option4: defaultValue4,
  option5: defaultValue5,
  option6: defaultValue6
 },options||{});
 // remainder of function...
}


创建jQuery命令实际上就是在jQuery.prototype上加入新的方法,一般的样式如下:



$.fn.wrapperFunctionName = function(params){function-body};


//形式2 jQuery命令,$.fn就是jQuery.prototype的别名


链接: 《jQuery in Action》 in action系列


0 Responses to "《jQuery in Action》 in Action - Chapter 7"

Post a Comment (友情提示:添加评论需要翻墙)