0

YUI の .on("click", ) を使用して関数に引数を渡すことは可能ですか? たとえば、ここに私が見ているいくつかのコードがあります:

function foo1() {
  var curObj = this;

    this.foo2 = function() {
         curObj.test = "foo2";
    }

    this.foo3 = function() {
         curObj.test = "foo3";
    }

  // called by
  this.blah = {};
  var blah = this.blah;
  blah['x'] = new YAHOO.widget.Button(x)
  blah['x'].on("click", foo2)

  blah['y'] = new YAHOO.widget.Button(y)
  blah['y'].on("click", foo3)
}

次のようなことをして、冗長性を取り除きたいと思います。

function setTest(this, foo) {
  this.test = foo;
}

function foo1() {
  var curObj = this;

  // called by
  this.blah = {};
  var blah = this.blah;
  blah['x'] = new YAHOO.widget.Button(x);
  blah['x'].on("click", thisTest("foo2"));

  blah['y'] = new YAHOO.widget.Button(y);
  blah['y'].on("click", thisTest("foo3"));
}

YUI が "this" オブジェクトを .on("click", function) から呼び出された関数に渡すことは、私の理解です。

ご協力いただきありがとうございます。

4

2 に答える 2

2

ここの API ドキュメントに従って、単一の引数を送信できます: http://developer.yahoo.com/yui/docs/YAHOO.util.Element.html#method_on

例えば:

function setTest(this, foo) {
  this.test = foo;
}

function foo1() {
  var curObj = this;

  // called by
  this.blah = {};
  var blah = this.blah;
  blah['x'] = new YAHOO.widget.Button(x);
  blah['x'].on("click", thisTest, "foo2");

  blah['y'] = new YAHOO.widget.Button(y);
  blah['y'].on("click", thisTest, "foo3");
}

複数の値を渡したい場合は、渡したいすべての値を含む配列またはオブジェクトを作成する必要があります。これは API の制限です。

于 2013-03-07T06:55:42.010 に答える
1

これを実現するには、JavaScriptクロージャを使用できます。これにより、イベントハンドラーにアクセスさせるパラメーターの数とタイプをより細かく制御することもできます。また、このメソッドはフレームワークに依存しません。

たとえば、質問で指定されたコードスニペットでは、thisTestは次のようにクロージャを実行できます。

var thisTest = function (arg1, arg2) {

    return function () { // handler function

        // arg1 and arg2 will be available inside this function.

        // also any arguments passed to the handler by the caller will be 
        // available without conflicting with arg1 or arg2.

    }
}

これを示すjsFiddleリンクを次に示します。 http://jsfiddle.net/M98vU/4/

ここで覚えておかなければならない2つのことは次のとおりです。

  1. クロージャを介してイベントハンドラをアタッチすることによって引き起こされる循環参照は、古い(ish)ブラウザでメモリリークを引き起こす可能性があります。不要な場合やページのアンロード時にハンドラーを切り離すのは良い考えかもしれません。

  2. 渡される固定/静的パラメーターは、ハンドラーをアタッチするときに既知(決定可能)である必要があります。

于 2013-03-07T07:35:46.703 に答える