ボイラープレート jquery プラグインのこの一般的な設計パターンに従いましたが、プロトタイプのどこからでもコンストラクター内で特権メソッド this.service() を呼び出すのに問題があります。プロトタイプの初期化だけでなく、プロトタイプ内から this.service() を呼び出すにはどうすればよいですか?
全体として、私がやろうとしているのは、プラグインのこのインスタンス内でのみ影響を受け、変更されるこのプラグインの変数にアクセスできるようにすることです。この変数を別の場所に配置する必要がありますか? 変数は、私のコードでは variableToAccess という名前です。多分私はこれですべて間違っています。ありがとう。
プラグインは次のように呼び出されます
$('article').comment();
ここにプラグインがあります
;(function ( $, window, document, undefined ) {
// Create the defaults once
var pluginName = 'defaultPluginName',
defaults = {
propertyName: "value"
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
var variableToAccess = false;//<----should this be somewhere else?
this.service = function() {
variableToAccess = true;
};
this.init();
}
Plugin.prototype = {
init: function() {
Plugin.prototype.doSomething();
},
doSomething: function() {
this.service()//<----doesn't work
}
}
$.fn["comment"] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})( jQuery, window, document );