In JQuery Extension Function, how do I access the instance options? -
i have jquery extension functions, not sure how access instance's options:
(function ($) { $.fn.myextension= function (methodoroptions) { if (methods[methodoroptions]) { return methods[methodoroptions].apply(this, array.prototype.slice.call(arguments, 1)); } else if (typeof methodoroptions === 'object' || !methodoroptions) { // default "init" return methods.init.apply(this, arguments); } else { $.error('method ' + methodoroptions + ' not exist on jquery.myextension'); } }; var methods = { init: function (options) { var defaults = { testoption: "test" }; options = $.extend(defaults, options); return this.each(function () { // code logic goes here } myfunction: function () { var optionval = options.testoption; } }; })(jquery);
so code throw error when call myfunction because not know "options" is.
store on element's data object. http://jsfiddle.net/u7qt5/
(function ($) { $.fn.myextension = function (methodoroptions) { if (methods[methodoroptions]) { return methods[methodoroptions].apply(this, array.prototype.slice.call(arguments, 1)); } else if (typeof methodoroptions === 'object' || !methodoroptions) { // default "init" return methods.init.apply(this, arguments); } else { $.error('method ' + methodoroptions + ' not exist on jquery.myextension'); } }; var methods = { init: function (options) { var defaults = { testoption: "test" }; return this.each(function () { var $this = $(this); $this.data("myextension",$.extend(defaults, options)); // code logic goes here }); }, myfunction: function () { var optionval = this.data("myextension").testoption; console.log(optionval); } }; })(jquery); $("body").myextension({testoption: "foobar!"}).myextension("myfunction");
Comments
Post a Comment