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

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -