2010年8月16日 星期一

Develop JQuery Plugin

Adding a new global function

//自訂 globalFunction
jQuery.globalFunction = function(){
alert('This is a global function!');
};
//呼叫寫好的 globalFunction
$.globalFunction();


另一種寫法 jQuery.extend

//自訂 globalFunction
jQuery.extend({
globalFunction: function(){
alert('This is a global function!');
}
});
//呼叫寫好的 globalFunction
$.globalFunction();


Add namespace

//自訂 Rex's plugin
jQuery.Rex = {
globalFunction: function(){
alert("This is a Rex's function!");
}
};
//呼叫寫好的 plugin
$.Rex.globalFunction();


Creating a utility method

//自訂 sum utility
jQuery.Rex = {
sum: function(array){
var total = 0;
jQuery.each(array, function(index, value){
total += value;
});
return total;
}
};
//呼叫寫好的 utility
var myArray = [1,3,5,7,9];
alert($.Rex.sum(myArray));


Creating a jQuery Object method

//自訂 object method "swapClass"
jQuery.fn.swapClass = function(classA, classB){
this.each(function(){
var element = jQuery(this);
if(element.hasClass(classA)){
element.removeClass(classA).addClass(classB);
}
else if(element.hasClass(classB)){
element.removeClass(classB).addClass(classA);
}
});
};
$(document).ready(function(){
$('#btnSwap').click(function(){
//呼叫"swapClass"
$('li').swapClass('red', 'yellow');
return false;
});
});


Method chaining

//自訂 object method "swapClass"
jQuery.fn.swapClass = function(classA, classB){
return this.each(function(){
var element = jQuery(this);
if(element.hasClass(classA)){
element.removeClass(classA).addClass(classB);
}
else if(element.hasClass(classB)){
element.removeClass(classB).addClass(classA);
}
});
};
$(document).ready(function(){
$('#btnSwap').click(function(){
//呼叫"swapClass"
$('li').swapClass('red', 'yellow').css('text-decoration','underline');
return false;
});
});


Design Pattern

//javascript class design pattern
var People = function(name){
this.name = name;
};
People.prototype = {
constructor: People,
sayHi: function(){
alert('hello! I am ' + this.name );
}
};

var Rex = new People('Rex');
Rex.sayHi();


//jQuery plugin design pattern (Object method)
(function($){
$.fn.setColor = function(color){
return this.each(function(){
var element = jQuery(this);
element.css('background-color',color);
});
};
})(jQuery);

$(document).ready(function(){
$('a').setColor('red').css('font-size','36px');
$('a:eq(0)').css('background','yellow');
});

沒有留言:

wibiya widget