JQuery and prototype namespace -
hello starting jquery plugins, having problems understanding namespace.
given example below, when enter "submit" function, how prototype instance inside submit function? "var self = this;" in other function? in method refers form element.
(function ($, window, document, undefined) { var pluginprototype = { init: function (options, element) { var self = this; $(element).find('form').submit(self.submit); self.othermethod(); }, submit: function(){ var self = this; // form element }, othermethod: function () { var self = this; // prototype }, } $.fn.pluginname = function (options) { return this.each(function () { var plugin = object.create(pluginprototype); plugin.init(options, this); $.data(this, 'pluginname', comment); // // $.data($(select)[0], 'comment'); }); }; $.fn.pluginname.settings = { }; }(jquery, window, document));
actually, there misunderstood concepts here:
there's no "prototype instance" in case. prototype property of functions when used constructors. in case, pluginprototype plain object, prototype object.prototype.
"this" keword containing current function execution context , can modified depending on how call given function.
i suggest reading bit jquery plugin development here: http://learn.jquery.com/plugins/
that said, can suggest typical approach:
have methods of plugin properties of "methods" object (your current pluginprototype)
implement logic inside $.fn.pluginname function handle different execution requests.
return this.each(function() { if (methods[method]) { return methods[method].apply(this, array.prototype.slice.call(parameters, 1)); } else if ( typeof method === "object" || ! method ) { return methods.init.apply(this, parameters); } else { $.error("method "+method+"does not exist on wonderful plugin"); } });
a. plugin initialization called via $("…").plugin({option: value, …});
b. plugin methods called via $("…").plugin("method name", argument1, argument2, …);
all methods called "this" pointing current jquery-wrapped dom element; so, call method inside method go with:
methods.methodname.call(this, argument1, argument2);
hope helps you.
Comments
Post a Comment