2017-05-09 8 views
0

これは何度か尋ねられていますが、どういうわけか、私のニーズに合った答えが見つからないので、ここに行きます。 jQueryプラグイン - インスタンス化されたオブジェクトのアクセス方法

(function(window, $){ 

    var MyPlugin = function(elem, options){ 
     this.elem = elem; 
     this.$elem = $(elem); 
     this.options = options; 
     this.metadata = this.$elem.data('popup-options'); 
     this.markup = '<div>some markup here</div>'; 
     this.popup = null; 
    }; 

    MyPlugin.prototype = { 
     defaults:{ 
      type: 'outer', 
      color: 'orange' 
     }, 

     init: function(){ 

      this.config = $.extend({}, this.defaults, this.options, this.metadata); 

      this.show(); 

      return this; 
     }, 

     show: function(){ 

      // some stuff to show the element 

     }, 

     hide: function(){ 

      // some stuff to hide the element 
     }, 


     someMethod: function(){ 

      // some other stuff the plugin does 
     } 


    }; 

    MyPlugin.defaults = MyPlugin.prototype.defaults; 

    $.fn.myPlugin = function(options){ 
     return this.each(function(){ 
      var thePlugin = new MyPlugin(this, options).init(); 
     }); 
    }; 

    window.MyPlugin = MyPlugin; 

}(window, jQuery)); 

は今のコードで私はこのようなプラグインを適用します:

var thePlugin = $(this).myPlugin(); 

はこれまでのところ、この作品

は、私が(ストリップダウン)このようになりますプラグインを作りました。

今のところ、私はプラグイン内の機能の1つに外部からアクセスしたいと思います(例:someMethod)。

私は好きそれを呼び出そうとしました:これの

thePlugin.someMethod();

または thePlugin.myPlugin.someMethod();

あるいは

thePlugin.myPlugin[0].someMethod();

どれも機能しません。

プラグインを初期化した後にアクセスできるようにするにはどうすればいいですか? これはまったく可能ですか?

+0

あなたは 'myPlugin.prototype.someMethod()'を試してみましたか? –

+0

それを試した、うまくいかなかった... :( – Swissdude

答えて

0

溶液を見いだした。

私はこのようなプラグインのリターン・ステートメントを変更する必要がありました:

$.fn.updPopup = function(options){ 
     return new UpdPopup(this, options).init(); 
}; 

これはプラグインの単一インスタンスのみを返します。

それから私はこのようにそれにアクセスすることができます

thePlugin.someMethod(); 

疑問は残る:どのように私は(どうやら私は推測する、オブジェクトの配列を返すこと)、元のreturn文でそれにアクセスするのでしょうか?

関連する問題