0

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");
});

また、私が行ったように、プラグインの前に要素変数を宣言するのは正しいですか?

4

3 に答える 3

0

ページ上の他のプラグインおよび JavaScript コードからプラグインを分離するには、プラグインに単一のスコープを使用する必要があります。

これは、プラグインを開発するための優れたチュートリアルです。

于 2013-01-24T00:33:02.890 に答える
0
  1. initメソッドでイベント ハンドラを宣言しますが、.on代わりに を使用し.bindます。これらは、プラグインの動作の一部としてボタンにバインドするイベントであると想定しています。
  2. プラグインは既存の DOM にまったく依存してはならないため、要素を宣言するのは正しくありません。
于 2013-01-24T00:33:03.320 に答える
0

You can fully define your private utility functions showAlert and mathWorks outside the init() method. Declaring them outside and defining inside offers no advantage and is potentially confusing.

Event handlers can be attached inside any method to which you pass a jQuery collection (or a utility function called by such a method). Inside the method be sure to have a return this.each(function(){...}) structure, thereby addressing all members of the collection, and returning it for method chaining.

于 2013-01-24T01:31:47.267 に答える