10 Things I Learned From The JQuery Source
From Paul Irish
一篇很棒的演講,由專家帶領我們從JQuery的原始碼中學習一些JQuery所用的JavaScript Pattern以及設計方式.
自從在OSDC2010上聽了Gugod的Less is More,JQuery這個框架的簡潔性以及設計的原則就一直吸引著我.
這個演講剛好讓我以後在用JQuery的時候能更輕易的去看source.
以下是筆記:
1.JQuery的Convention之一: Closure Pattern:
(function(){ ... })();
!function(){ ... }()
後面的括號代表這是self executing function: run itself immediately
favorite pattern:
(function(window,document,undefined){
....
})(this,document)
把window,document當成變數傳入closure,這樣的好處是:
1.如果有其他全域變數例如 undefined = true; // break all undifined comparison
而closure避免了這些干擾
2.minification:
最佳化後會變成: function(A,B,C){}(this,document), 可以省下一些字元
2. async recursion
Self repeating: 會不斷的執行,不論前一項有沒有執行完,
例如
setInterval(function(){
doStuff();
},100) // is very evil
而self executing function能確保執行到尾巴之後才會執行第二遍
(function loops(){
doStuff();
$('#update').load('awesomething.php',function(){
loops();
})
setTimeout(loops,100);
})()
3.如何找到函式: 找 function name + : , ex: "noConflict:"
4.Jquery.noConflict:
在開始時將 原本的 $ 儲存為 _$, 並在呼叫noConflict時復原.
5.jQuery.props
小型的參數字典,自動將Html與Dom Api上一些相同意思但名稱不同的參數作對應
讓開發者不需要記得所有的東西.
也可以用在.attr:
ex: WAI ARIA
$(elem).attr('aria-disabledby','asdasdasd');
$.props['adb'] = 'aria-disabledby';
=>
$(elem).attr('adb') = 'asdasdasd';
6. fadeIn() : defined your own speeds:
JQuery內部的 speed 定義了各種速度:
speeds: {slow:800 ,fast:200 ,_default:800}
可以由外部加入自訂的速度
jQuery.fx.speeds.fastopen= ($.browser.msie && $.browser.version < 8 ) ? 800 : 400;
//在IE7以下速度為800,其他瀏覽器為400
$('#stuff').fadeIn('fastopen');
7.JQuery.ready(...) 會檢查DOM準備好沒,在準備完畢時執行function,bindReady(); // IEContentLoad: solve by great Italian hacker,
using doScroll check to check if DOM ready in IE :
doScroll(left); //will raise exception if DOM not ready.
8.getJSON : shorthand methods:
jQuery ajax() holds anything, but get,post,getJSON,getScript shorten the varible.
9.selector performence.
$('#id') vs $('#id tag.thing')
$('#id tag.thing') will self parse to => $('#id').find('tag.thing');
$('#id').find('tag.thing')
$(':password') === $('*:password')
so better provide tagname ex: $('input:password');
10.getJSON: function protect 會用regex檢查資料是否為JSON,如果是的話就pass,
不是的話會呼叫 (new Function("return" + data))();
這叫Function constructor: 回傳
function(){return data;}
=== eval('('+data')');
但是避開使用邪惡的eval
11 $.unique(err) : duck punch
$.unique能夠過濾相同的DOM元素,讓陣列只有unique的元素
但不對應基本物件 使用duck punch來擴充unique方法:
(function($){
_old = $.unique()
if(!!arr[0].nodeType){
return _old.apply(this,arguments);
} else {
return $.grep(arr,function(v,k){
return $.inArray(v,arr) === k
});
}
})(jQuery);
12.quene: $(elem).fadeIn().delay(1000).fadeOut(); 可以使用quene方法改寫成
$(elem).quene(function(){
$(elem).delay(1000).fadeOut();
});
13.$.support
support使用一個HTML div,內部包含table,/a等等各項元素,
support會檢查瀏覽器能不能辨識其中的元素,來做瀏覽器的相容性檢查
14.bit.ly/jqsource : 一起來看JQuery Source
No comments:
Post a Comment