I’ve been reading about jQuery plugins for a while and trying to implement our plugins in a more oop way.
my manager is a c# guy and hates the way jQuery UI calls methods.
i wanna use the approach bellow and wanna know your opinion about it.
tell me the pros and cons of what i’m trying to use plz.
ok this is it as a simple sample.it has works to do but for start:
if(typeof Object.create !== 'function')
{
Object.create = function(o)
{
function F()
{
}
F.prototype = o;
return new F();
};
}
var Car = (function()
{
var openDoor = function(doorNum)
{
alert("door #" + doorNum + " opened");
};
return {
openDoor: openDoor
};
}
)();
(function($, window, document, undefined)
{
$.fn.car = function(options)
{
if(this.length)
{
return this.each(function() {
var myCar = Object.create(Car);
$.data(this, 'car', myCar);
for(var prop in Car)
{
if($.fn[prop] == null)
{
$.fn[prop] = function(params)
{
return this.each(function () {
if($.data(this, "car") == null)
{
throw Error("not implemented function");
}
$.data(this, "car")[prop](params);
}
);
};
}
}
});
}
};
})(jQuery, window, document);
$("#test").on("click", function()
{
$("#test").car().openDoor(1).css({color: 'red'});
});
and here is the fiddle link
http://jsfiddle.net/6zHP7/8/
Great undertaking! I have the same quirk as your boss where I do not feel jQuery’s plugin interface is sufficient for advanced plugins.
I have started a GitHub project just for this purpose: to give jQuery plugins a more OOP API while remaining backwards compatible.
https://github.com/adamovsky/jQuery-Plugin-Pattern
I also started writing a blog post that will go with it:
http://milan.adamovsky.com/2012/12/jquery-plugin-pattern-30.html
Feel free to join the effort and contribute.
Some of the issues I see with your pattern are addressed in my pattern – such as the use of .data(). The other issue I see is that each call to your plugin will instantiate the class.
All in all, it’s quite an ambitious thing to do and more difficult than it looks due to the edge use cases that can easily make your plugin crash and burn if not addressed (as I found out in my earlier attempts at marrying OOP with jQuery).
Milan