You should stay more close to the common jQuery plugin pattern.
// method is an (optional) string to call a special method on each element
// options is an (optional) object to add or overwrite properties of the defaults
$.fn.myPlugin = function(method, options) {
if (typeof method == 'object') options = method, method = null;
var settings,
defaults = {
events: {click: function() {$(this).css({backgroundColor: settings.backgroundColor});}},
backgroundColor: 'red',
border: '2px solid black',
/* all your defaults here */
},
methods: {
giveBorder: function() {$(this).css({border: settings.border});}
/* all your named methods here, you can use values from settings inside*/
}
settings = $.extend(true, {}, defaults, options); // merge defaults and options together
// now apply a function to each element and return the whole collection
// if there's a valid method do this
if (method && methods[method]) return this.each(methods[method]);
// otherwise do the initializing function
else return this.each(function(i, elem) { // this 'is' the initializing function
// put in here all you want to do with each element on init
$.each(settings.events, function(evt, func) { // apply the event handler to each element
if (typeof func == 'function')elem.on(evt, func);
})
})
};
When you now do on the li-elements $('li').myPlugin() all single elems get a click-handler attached. But $('li') is not live, it holds only the elems beeing in the DOM when it's called (old versions of jQuery had a .live()-function but that was deprecated and removed).
So when you want to initialize a newly created elem with your plugin do it this way:
var alllis = $('li').myPlugin();
var newli = $('<li>Dynamic</li>').myPlugin(); // now it has also a click-handler
$('ul').append(newli); // now it's added to the DOM
alllis.add(newli); // this way you can add it to the jQuery collection of all li
Here' is a working DEMO, and you should play around with following to evaluate the possibilities of this pattern:
var newli2 = $('<li>DynamicGreen</li>').myPlugin({backgroundColor: 'green'});
var newli3 = $('<li>DynamicMouseover</li>').myPlugin(
{events: {click: 'none', mouseover: function() {$(this).css({backgroundColor: 'yellow'})} }}
);
newli3.myPlugin('giveBorder');
$('ul').append(newli2, newli3);
<li>the background for that element should change, not all of them. The dynamic<li>'s background never changes.