1. Be lazy
JQuery ควรจะเรียก fuction โดยตรงไม่จำเป็นต้องมีการตรวจสอบซ้ำซ้อน
// Don't
if ($('#item').get(0)) {
$('#item').someFunction();
}
// Or
if ($('#item').length) {
$('#item').someFunction(); }
// Just do
$('#item').someFunction();
2. Use shortcuts
เลือกที่จะเขียนแบบลัด เร็วกว่าที่จะเขียนแบบยาว โดยที่มีความหมายเหมือนกัน
// You can but..
$(document).ready(function(){
// ...
});
// There is a shorter equivalent
$(function(){
// ...
});
3. Chain
จุดเด่นข้อหนึ่งของ Jquery คือการเขียนแบบต่อเนื่องหรือการเขียนแบบห่วงโซ่
// Don't
$('#frame').fadeIn();
$('#frame .title').show();
$('#frame a:visited').hide;
// Do
$('#frame').fadeIn()
.find('.title').show().end()
.find('a:visited').hide();
4. Group queries
การ selector แบบกลุ่มเราสามารถใช้เครื่องหมาย , (comma) หมายถึง Or (หรือ)
// Ugly
$('div.close').click(closeCallback);
$('button.close').click(closeCallback);
$('input.close').click(closeCallback);
// Not ugly
$('div.close, button.close, input.close')
.click(closeCallback);
5. Select siblingd like a pro
// Don't
$('#nav li').click(function(){
$('#nav li').removeClass('active');
$(this).addClass('active');
});
// Do
$('#nav li').click(function(){
$(this).addClass('active')
.siblings().removeClass('active');
});
6. Use each and map
ควรใช้ $.each หรือ $.map กับ Array Object
// Try to avoid
var output = [];
for (var i=0;i < arr.length; i++) {
output.push(arr[i]);
}
// Do
var output = $.map(arr, function() {
...
});
// Or
var output = [];
$.each(arr, function(index, value) {
output.push(value);
});
7. Use namespace
การกำหนด namespace ใน event
$('input').bind('blur.validation', function(e){
// ...
});
ใน data method ยอมรับการใช้ namespaces
$('input').data('validation.isValid', true);
8. triggerHandler is great
triggerHandler มีประโยชน์ในการสร้าง custom events แทนที่เราจะเขียนแบบนี้
var refreshFrame = function() {
$('#frame').load('http://reddit.com');
};
$('.button').click(refreshFrame);
refreshFrame();
เราควรจะเขียนแบบนี้
$('.button').click(function() {
$('#frame').load('/page/frame.html');
}).triggerHandler('click');
// You can also use a shortcut
$('.button').click(function() {
$('#frame').load('/page/frame.html');
}).click();
9. Custom events
ในบางสถานการณ์ครั้งมันอาจจะช่วยเรามาก อย่างเช่น การห่อหุ้ม(Encapsulate) plugins
$('.button').click(function() {
$('div#frame').load('/page/frame.html', function(){
$(this).triggerHandler('frameLoaded');
});
});
// PluginA.js
$('#frame').bind('frameLoaded', function(){
$(this).show('slide', {direction: 'top'});
});
// PluginB.js
$('div').bind('frameLoaded', function(){
// do something else
});
10. Test
JQuery สามารภทำ Unit Testing ได้จาก QUnit เช่น
module("A simple test");
test("The frame should appear #button is clicked", function() {
expect(1);
$('#button').click();
ok($('#frame').is(':visible'), "The frame is visible" );
});
Reference Site : http://haineault.com/blog/84/
