web-dev-qa-db-ja.com

JQueryプラグイン内にネストされている関数を呼び出す方法は?

私の目標は、JQueryプラグイン内にある関数を呼び出せるようにすることです。

正しい構文は何ですか?

たとえば、これは機能しません。

<a href="#" id="click_me">Click Me</a>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
(function($) { 
    $.fn.foo = function(options) {
        do_stuff = function(){
            console.log("hello world!"); // works
            do_other_stuff = function(){
            alert("who are you?");
            }
        } // function
    } // function
})(jQuery);

$("body").foo();

$("#click_me").click(function(){
$.fn.foo.do_stuff.do_other_stuff(); // doesn't work
});

</script>
15
edt

varキーワードを使用せずに変数に関数を割り当てると、その名前のローカル変数が上書きされるか、グローバル名前空間に追加されます。 (つまり、do_stuffはグローバル関数であり、必要なものではありません)

必要なことを行う1つの方法は、関数を配置する場所を明示的に指定することです。

(function($) { 
    $.fn.foo = function(options) {
        // whatever $().foo() should do
    };

    $.fn.foo.do_stuff = function() {
        console.log("hello world!");
    };

    $.fn.foo.do_stuff.do_other_stuff = function(){
        alert("who are you?");
    };
})(jQuery);

編集

これは、javascriptのすべての関数がオブジェクトであるために機能します。つまり、任意のプロパティに値を割り当てることができます。

他の関数の変数にアクセスしたい場合は、次のように他の関数内で定義を移動できます。

$.fn.foo.do_stuff = function() {
    console.log("hello world!");
    $.fn.foo.do_stuff.do_other_stuff = function(){
        alert("who are you?");
    };
};

ただし、これは、関数が他の関数を実行したときにのみ定義され、関数を実行するたびに最後の定義が上書きされることを意味します。

おそらく、より理想的な解決策は、次のように、各関数にネストされた関数を含むオブジェクトを返すようにすることです。

(function($) { 
    $.fn.foo = function(options) {
        // whatever $().foo() should do

        var do_stuff = function(do_stuff_args) {
            console.log("hello world!");
            // do stuff with options and do_stuff_args

            var do_other_stuff = function(other_args) {
                alert("who are you?");
                // here you have access to options, do_stuff_args, and other_args
            };

            return {
                do_other_stuff: do_other_stuff
            };
        };

        return {
            do_stuff: do_stuff
        }
    };
})(jQuery);

を使用してそれを呼び出す

foo().do_stuff(some_options).do_other_stuff(other_options);

または

var a = foo(stuff).do_stuff(some_options);
a.do_other_stuff(foo);
a.do_other_stuff(bar);
36
cobbal