2013-05-08 27 views
0

我有功能的JQuery的擴展,我不知道如何訪問實例的選項:在JQuery擴展函數中,如何訪問實例選項?

(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 to "init" 
      return methods.init.apply(this, arguments); 
     } else { 
      $.error('Method ' + methodOrOptions + ' does 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); 

所以這個代碼拋出一個錯誤,當我打電話MyFunction的,因爲它不知道什麼是「選擇」是。

回答

1

將其存儲在元素的數據對象上。 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 to "init" 
      return methods.init.apply(this, arguments); 
     } else { 
      $.error('Method ' + methodOrOptions + ' does 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"); 
0

所以,這只是一個簡單的範圍界定問題,我相信。你有對象選項被傳遞到init,但它是本地的功能。您需要將其放在對象上,以便您的其他功能MyFunction具有適用範圍。

var methods = { 
    init: function (options) { 
     var defaults = { 
      testOption: "test" 
     }; 
     this.currentOptions = $.extend(defaults, options); 

     return this.each(function() { 
      // Code logic goes here 
     } 

    MyFunction: function() { 
     var optionVal = this.currentOptions.testOption; 
    } 
};