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() メソッドを使用する方法はありますか?