How to make a jQuery plugin (the right way)?
- by macek
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($){
$.cookie = function(name, value, options) {
if (typeof value == 'undefined') {
return get(name);
}
else {
options = $.extend({}, $.cookie.defaults, options || {});
return (value != null) ? set(name, value, options) : unset(name, options);
}
};
$.cookie.defaults = {
expires: null,
path: '/',
domain: null,
secure: false
};
var set = function(name, value, options){
console.log(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(';');
};
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);