I am trying to tackle two fairly massive concepts through JavaScript and jQuery, the first being object-oriented programming and the second being how to build robust modular plugins with an OOP approach. So far I've learned it's hard.
Here is an example plugin I built, that I somewhat based my much larger project on; any opinions you guys have on my approach would be awesome.
;(function($, window, document, undefined) {
"use strict";
$.fn.myPlugin = function(opts) {
var settings = $.extend({},{ color : 'blue', normal : 'black' }, opts);
var proto = {
show : function () { $(this.self).css( "color", this.settings.color ); },
hide : function () { $(this.self).css( "color", this.settings.normal); },
log : function () { console.log(this); }
}
return this.each(function(id, elem) {
if (!$.data(elem, 'parent')) // Base parent object
$.data(elem, 'parent', Object.create(proto, {
'settings' : { value : settings,
writable : true,
enumerable : true,
configurable : true
}
}));
$(elem).children('span').each(function(idx, elmx) {
if (!$.data(elmx, 'child')) // Child obj w/ delegation from parent
$.data(elmx, 'child', Object.create($.data(elem, 'parent'), {
'foo' : { value : 'bar',
writable : true,
enumerable : true,
configurable : true
},
'self' : { value : elmx,
writable : false,
enumerable : true,
configurable : false
}
}));
$(elmx).hover(
function() {
$.data(elmx, 'child').log();
$.data(elmx, 'child').show();
}, function() {
$.data(elmx, 'child').hide();
});
});
});
};
}(jQuery, window, document));
Here is where the code is running, basically all it does is search for <span>
tags inside of the <p>
tags the plugin is instantiated on and highlights them with a given user setting or the defaults. It shows the use of delegation for inheritance and very basic event management (no callbacks as of yet)