jQuery ドキュメントからプラグインを作成するための手順に従っています。セクション 6.1 で指示されているように、呼び出しを同じ名前空間に保持しようとしていますが、各呼び出しでより多くのオプションを通過できるようにする必要もあります。
やりたいこと
$('#element').myFunction({
method: 'method1',
option1: 'option1',
option2: 'option2'
});
私が現在持っているもの
(function($) {
var methods = {
init: function(options) {
//initialization
},
method1: function(options) {
var settings = $.extend({
'option1' = 'option default',
'option2' = 'option 2 default'
}, options);
//use settings for given method ex: settings.option1, settings.option2
}
};
$.fn.myFunction(options) {
//method logic
if(methods[options.method]) {
return methods[options.method].apply(this, Array.prototype.slice.call(arguments, 1)); //I'm thinking I need to do something here to pass through the options to the methods???
} else if (typeof options.method === 'object' || !options.method) {
return methods.init.apply(this, arguments); //or possibly here?
} else {
$.error('Method ' + options.method + ' does not exist on jQuery.myFunction');
}
};
})(jQuery);
私はしばらくフロント エンドの Web 開発を行っていませんでしたが、もう一度やり直そうとしていますが、メソッド ロジックのセクションはやや混乱しています。でどのような処理が行われているのかを理解する必要がありmethods[options.method].apply()
ます。これが各メソッドが呼び出される場所であることは知っていますが、追加のオプションがどこに渡されるかはわかりません。
[アップデート1]
で何が起こっているかについてもう少し読んだapply()
ことがありますが、オブジェクトやその他の引数を通過すると信じています。私はそれをに変更しようとしましたmethods[options.method].apply(this, options);
が、これは私の問題を修正していないようです.
【アップデート2】
次の変更を加えることで、コードが機能するようになりました
var methods = {
init: function(options) {
//initialization
},
method1: function(element, options) {
var settings = $.extend({
'option1' = 'option default',
'option2' = 'option 2 default'
}, options);
//use settings for given method ex: settings.option1, settings.option2
element.each(function() {
};
}
};
$.fn.myFunction(options) {
//method logic
if(methods[options.method]) {
return methods[options.method](this, options); // apply(this, Array.prototype.slice.call(arguments, 1)); //I'm thinking I need to do something here to pass through the options to the methods???
} else if (typeof options.method === 'object' || !options.method) {
return methods.init.apply(this, options); // arguments); //or possibly here?
} else {
$.error('Method ' + options.method + ' does not exist on jQuery.myFunction');
}
};
元のコードが何をしようとしていたのか、私の変更と比較して説明したい人は誰でも、それを答えとして受け入れます。