如何使我的插件选项可用于所有插件?

时间:2012-11-11 03:16:56

标签: jquery jquery-plugins plugins



我开始制作插件,我在插件中遇到了变量范围问题。我希望能够从插件中的任何位置访问我的选项,但不知道如何,var $ opts只对该函数可见,我的公共函数无法访问它。有谁知道我会怎么做?

提前致谢,哦,如果有人注意到任何错误,我会让插件毫不犹豫地提及它们:D

//@@@@ Start of myViewport Plugin @@@@\\
(function($) {

  $.fn.myViewport = function(options) {
    var $opts = $.extend({}, $.fn.myViewport.defaults, options);

    //Plugin Here
    return this.each(function() {           

        alert('Initialising Plugin!' + $opts.privateText + $opts.publicText);
        myPrivateFunction();
    });
  };

  // private functions
  function myPrivateFunction($opts) {
        alert($opts.privateText);
  };

  // public functions
  $.fn.myViewport.myPublicFunction = function() {
        alert($opts.publicText);
  };

  // plugin defaults
  $.fn.myViewport.defaults = {
    privateText: 'This is a text from the privateText defaults',
    publicText: 'This is a text from the publicText defaults'
  };

})(jQuery);
//@@@@ End of myViewport Plugin @@@@\\

1 个答案:

答案 0 :(得分:1)

像这样:

(function($) {

  $.fn.myViewport = function(options) {
    var o = $.extend(vp, $.fn.myViewport.defaults, options);

    //Plugin Here
    return this.each(function() {           

        alert('Initialising Plugin!' + o.privateText + o.publicText);
        myPrivateFunction();
    });
  };

  var vp = $.fn.myViewport;

  // private functions
  function myPrivateFunction() {
        alert(vp.privateText);
  };

  // public functions
  vp.myPublicFunction = function() {
        alert(vp.defaults.publicText);
  };

  // plugin defaults
  vp.defaults = {
    privateText: 'This is a text from the privateText defaults',
    publicText: 'This is a text from the publicText defaults'
  };

})(jQuery);

演示here