ここに表示されるのは、プラグインから始める方法です。
(function($){
var methods = {
init: function(){
$this = this;
alert('init '+$this.attr('id'));
}
,
show_id: function(){
alert($this.attr('id'));
}
};
var $this;
// other vars
$.fn.my_plug = function(method){
var args = arguments;
var $this = this;
return this.each(function(){
if (methods[method]){
return methods[method].apply($this, Array.prototype.slice.call(args, 1));
} else if (typeof method === 'object' || !method){
return methods.init.apply($this, Array.prototype.slice.call(args, 0));
} else {
$.error('Method '+method+' does not exist!');
}
});
};
})(jQuery);
var a = true;
if (a) $('#object').my_plug(); // alerts "init object"
$('#object').my_plug('show_id'); // alerts "object"
var b = false;
if (b) $('#object_b').my_plug(); // does nothing
$('#object_b').my_plug('show_id'); // calls "show_id"-method … but $this is not defined. It should NOT call because this object is not initialized !!!
下部に、プラグイン メソッドの呼び出し方法が表示されます。
最初の質問:「これ」/メソッド内のオブジェクトを取得するよりクリーンな方法はありますか? 最初にプラグインの外側で var を定義し、次にプラグインの内側で、次に init-function の内側で定義するのは非常にクールではないと思います。これを行うためのよりクリーンな方法はありますか?
下部にあるように、if ステートメントが true の場合にのみプラグインを呼び出します。true の場合は、init を呼び出します。次に、「$this」が以前に定義/初期化されているため、これも正常に機能するプラグインのメソッドを呼び出します。しかし、if ステートメントが真ではなく、プラグインの「init」メソッドが呼び出されていない場合…プラグインのメソッドを呼び出すことができるのは論理的ではないと思います。
質問 #2: オブジェクトが初期化されていない場合、メソッドの呼び出しを防ぐにはどうすればよいですか? プラグインを初期化していないため、呼び出し$('#object_b').my_plug('show_id');
ても何もしないはずです。プラグインが初期化されている場合、または "$this" が定義されている場合にのみ使用できます。
どう思いますか?