2014-06-08 2 views
0

나는 다음 상용구를 사용하여 jQuery 플러그인을 만드는거야 :공개 플러그인 방법으로 jQuery 플러그인 설정에 액세스하는 방법은 무엇입니까?

https://github.com/jquery-boilerplate/jquery-boilerplate/blob/master/src/jquery.boilerplate.js

내 질문 내 플러그인의 추가 공개 방법이있는 경우, 어떻게 플러그인의 설정 (및 기타 변수)에서 액세스합니까 그 공용 방법 안에서?

;(function ($, window, document, undefined) { 
    // Create the defaults once 
    var pluginName = "myplugin", 
    defaults = { 
     propertyName: "value" 
    }; 

    // The actual plugin constructor 
    function Plugin (element, options) { 
     this.element = element; 
     this.settings = $.extend({}, defaults, options); 
     this._defaults = defaults; 
     this._name = pluginName; 
     this.init(); 
    } 

    var body = $('body'); 

    Plugin.prototype = { 
     init: function() { 
      // Init code here 
     }, 
     yourOtherFunction: function() { 
      // This is a private method 
     } 
    }; 

    // Toggle menu opening 
    $.fn.doSomething = function(){ 
     // How do I access the plugin's settings here? <<<<<<< Here is the issue 
    }; 

    // A really lightweight plugin wrapper around the constructor, 
    // preventing against multiple instantiations 
    $.fn[ pluginName ] = function (options) { 
     this.each(function() { 
      if (!$.data(this, "plugin_" + pluginName)) { 
       $.data(this, "plugin_" + pluginName, new Plugin(this, options)); 
      } 
     }); 

     // chain jQuery functions 
     return this; 
    }; 

})(jQuery, window, document); 

그래서 나중에 내가 $('.myelement').doSomething();을하고 그 방법으로 할 수 $('.myelement').myplugin();를 사용하여 내 플러그인을 instaniating 후, 나는 플러그인의 설정에 액세스 할 수 있어야합니다. 어떻게해야합니까? this.settings이 작동하지 않는 것으로 나타났습니다.

더 나은 대체 플러그인 상용구가 있습니까? 아니면이 표준이 있습니까?

답변

0

나쁜 디자인입니다. 완전히 새로운 플러그인을 만들고 있습니다. 그리고 myplugindoSomething 사이에는 연결이 없습니다.

나는이 작업을 수행하는 것이 좋습니다 것입니다 : 위의 구문을 사용하는 경우

$.fn[ pluginName ] = function (options) { 
    if(options == 'doSomething'){ 
     // do something here or call some predefined function here 
    } 
    else{ 
    this.each(function() { 
     if (!$.data(this, "plugin_" + pluginName)) { 
      $.data(this, "plugin_" + pluginName, new Plugin(this, options)); 
     } 
    }); 
    } 
    // chain jQuery functions 
    return this; 
}; 

그래서, $('.myelement').myplugin();를 호출 한 후, 당신은 할 수 있습니다 : 당신은 옵션 대신 문자열을 전달하는

$('.myelement').myplugin('doSomething'); //this is cool! 
+0

을 인스턴스화시. 그게 맞습니까? 공개적으로 액세스 할 수있는 여러 메소드가있는 곳에서는 다른 플러그인이 어떻게 사용합니까? –

관련 문제