0

jQuery.on() でそれを使用して jQuery.proxy() メソッドをさらに進めようとしていますが、複数の「this」が含まれているため、ある時点で立ち往生しています。

これは jQuery.proxy() を使用する古典的な方法です:

var obj = {
  somevar: 'some value',
  doSomething: function() {
    alert(this.somevar);
  }
};
$('div').click( $.proxy(obj.doSomething, obj) ); // -> 'some value'

わかりましたが...「div」から情報を取得して「doSomething」に送信したいと思います...

function Foo(element) {
  this.element = element;
  this.init();
}
Foo.prototype = {
  init: function () {
    this.element.on('click', 'button', $.proxy(function () {
      // trying to send the type of the button to the doSomething method
      this.doSomething( $(this).attr('type') );
    }, this));
  },
  doSomething: function (data) {
    alert(data); // -> 'undefined'
  }
};

var Bar = new Foo( $('div') );

もちろん、「$(this)」内の「this」は jQuery ボタン オブジェクトではないため、機能しません。私が見つけた唯一の解決策は、「init」メソッドを少し変更することです。

  init: function () {
    var that = this;
    this.element.on('click', 'button', function () {
      that.doSomething( $(this).attr('type') );
    });
  },

この「その」変数の代わりに $.proxy() メソッドを使用する方法はありますか?

4

1 に答える 1

1

イベントハンドラーに別のをバインドすると、当然、イベントが発生した要素を参照するためにthis使用できなくなります。this代わりに、ハンドラーに渡されたイベント引数 (たとえば、e)を受け入れ、 e.target(イベントが発生した要素) またはe.currentTarget(イベントをフックした要素。通常thisは使用しない場合) を使用します。$.proxy)。

たとえば、次のことを考慮してください。

<div id="foo"><span>Click here</span></div>

$("#foo").on("click", $.proxy(function(e) {
    // code here
}, someObject));

span上記 (テキスト)をクリックすると、Click hereas ofはスパン (イベントが実際に発生した場所)、は(イベントをフックした場所)、もちろんはです。code heree.targete.currentTargetdivthissomeObject

実例| ソース

于 2013-10-28T22:29:16.517 に答える