jQueryプラグインの開発を学ぼうとしています。jQuery サイトの基本チュートリアルを読み、それがどのように機能し、プラグインがどのように構成されているかを理解しようとしました。
私はいくつかの高速テストを行いましたが、今は立ち往生しており、どうすれば乗り越えられるかわかりません。
コードは次のとおりです。
var myElement = $("#Foo");
var myButton = $("#Bar");
(function($) {
var showAlert;
var mathWorks;
var methods = {
init : function(options) {
// Declaring Default Options
var defaults =
{
option1 : 'Default',
option2 : false
}
// Merge Options
var opt = $.extend(defaults, options);
showAlert = function(txt)
{
alert(txt);
}
mathWorks = function(a,b)
{
alert('Result of '+a+'*'+b+' = '+ a*b);
}
methods.doSomething(opt.option1);
},
doSomething: function(text)
{
alert(text);
},
doMathWorks: function(a,b)
{
mathWorks(a,b)
}
};
$.fn.testPlugin = function() {
var method = arguments[0];
if(methods[method]) {
method = methods[method];
arguments = Array.prototype.slice.call(arguments, 1);
} else if( typeof(method) == 'object' || !method ) {
method = methods.init;
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.pluginName' );
return this;
}
return method.apply(this, arguments);
}
})(jQuery);
イベントハンドラはどこで宣言しますか?
お気に入り:
myButton.bind('click', function()
{
alert('test');
//methods.doSomething("Testing");
});
また、私が行ったように、プラグインの前に要素変数を宣言するのは正しいですか?