I'm writing a plugin that will display a little helper when called for. It's supposed to be initiated like this:
$(el).santasLittleHelper([options])
The plugin then have some "events" just like the jquery UI has and they should be triggered like this:
$(el).santasLittleHelper('evetnName', [options])
I have a prototype working 开发者_高级运维but I have a few concerns about future problems with my structure. Flooding the memory or having other issues with variable and function scopes when I keep on working on it. Here is an outline:
(function($) {
$.fn.santasLittleHelper = function(p1, p2) {
return this.each(function() {
var o = {
showSpeed: 50,
hideSpeed: 50,
duration: 5000,
delay: 0
}
var el = $(this);
function init() {
console.log('init 1');
}
var events = {
show: function(opt) {},
hide: function(opt) {},
pulse: function(opt) {}
}
if(p1 == undefined) {//This is obviously the init call
init();
}
if(typeof(p1) == 'object') {
//Correctly added parameters would then mean that p1 is options
//and is the only parameter added so we store the options and init
$.extend(o, p1);
init();
}
if(typeof(p1) == 'string') {
//This is a call to an "event".
//call the "event" function and supply possible options as arg
events[p1](p2);
}
});
}
})(jQuery);
Options can be supplied for each event call but should in that case only be available in that events function scope. This is because I might want the helper to do something out of the mental box I created him in by supplying options in the init call.
Will this approach fill up the memory a little by each call to $(el).santasLittleHelper('event') because of the declared variables in the beginning of the code?
I think it looks clean and understandable, but can improvements be done?
According to practices described here, it seems to me that you're doing it right, but I would try if possible to make o and events independent of each (declare it before and pass as optional parameter if override is needed else use unique declared outside of each?)
精彩评论