How to make a jQuery plugin (the right way)?
I know there are jQuery cookie plugins out there, but I wanted to write one for the sake of better learning the jQuery plugin pattern.
I like the separation of "work" in small, manageable functions, but I feel like I'm passing name
, value
, and options
arguments around too much. Is there a way this can be refactored?
I'm looking for snippets of code to help illustrate examples provided with in answers.
Any help is appreciated. Thanks :)
example usage
$.cookie('foo', 'bar', {expires:7});
$.cookie('foo'); //=> bar
$.cookie('foo', null);
$.cookie('foo'); //=> undefined
Edit:
I did a little bit of work on this. You can view the revision history to see where this has come from. It still feels like more refactoring can be done to optimize the flow a bit. Any ideas?
the plugin
(function($){
// the utility function
$.cookie = function(name, value, options) {
// cookies enabled?
if (!navigator.cookieEnabled){
return false;
}
// get
if (typeof value == 'undefined') {
return get(name);
}
// set
else {
options = $.extend({}, $.cookie.defaults, opt开发者_开发知识库ions || {});
return (value != null) ? set(name, value, options) : unset(name, options);
}
};
// default options
$.cookie.defaults = {
expires: null,
path: '/',
domain: null,
secure: false
};
// private functions
var set = function(name, value, options){
return document.cookie = options_string(name, value, options);
};
var get = function(name){
var cookies = {};
$.map(document.cookie.split(';'), function(pair){
var c = $.trim(pair).split('=');
cookies[c[0]] = c[1];
});
return decodeURIComponent(cookies[name]);
};
var unset = function(name, options){
value = '';
options.expires = -1;
set(name, value, options);
};
var options_string = function(name, value, options){
var pairs = [param.name(name, value)];
$.each(options, function(k,v){
pairs.push(param[k](v));
});
return $.map(pairs, function(p){
return p === null ? null : p;
}).join(';');
};
// prepare each key=value pair
var param = {
name: function(name, value){
return name + "=" + encodeURIComponent(value);
},
expires: function(value){
// no expiry
if(value === null){
return null;
}
// number of days
else if(typeof value == "number"){
d = new Date();
d.setTime(d.getTime() + (value * 24 * 60 * 60 * 1000));
}
// date object
else if(typeof value == "object" && value instanceof "Date") {
d = value;
}
return "expires=" + d.toUTCString();
},
path: function(value){
return "path="+value;
},
domain: function(value){
return value === null ? null : "domain=" + value;
},
secure: function(bool){
return bool ? "secure" : null;
}
};
})(jQuery);
This is an excellent tutorial on using TDD to turn your jquery code into a richer unit testable plugin
http://net.tutsplus.com/articles/news/learn-how-to-create-a-jquery-plugin/
This will help u..
精彩评论