いくつかのjquery関数をjavascriptオブジェクトに移動していくつかのコードをクリーンアップします。私の問題は、オブジェクトのコンストラクタにメソッドを置くと、イベントハンドラはイベントに応答しないようですが、ハンドラがヘルパーメソッドであり、オブジェクトのコンストラクタの外側にある場合にはうまく反応します。オブジェクト指向のjquery - イベントハンドラが動作しない
ここではこれを使用するときは、私のコードが出てエラーや機能の実行の上console.log
年代を入れていない
function MyConstructor() {
this.init();
this.selectAllHandler();
}
MyConstructor.prototype = {
init: function() {
$(document).on('click', '#my_element', this.selectAllHandler);
},
selectAllHandler: function() {
// some code in here
}
}
が動作していない私のコードです。しかし、私がハンドラをトリガするものをクリックしようとすると、何もしません。
しかし、オブジェクトの外側のメソッドを使用してコンストラクタとして構築すると、正常に動作します。このように
function MyConstructor() {
this.init();
}
MyConstructor.prototype = {
init: function() {
$(document).on('click', '#my_element', selectAllHandler);
}
}
function selectAllHandler() {
// code that works fine
}
私はオブジェクトのプロトタイプ内部でハンドラを呼び出すことができません。
編集
は、ここに私の新しいコードです。問題は現在、$(this)
はコンストラクタを参照しているようで、クリックされた要素を参照していないようです。
function MyConstructor() {
this.init();
}
MyConstructor.prototype = {
init: function() {
$(document).on('click', '#my_element', this.selectAllHandler.bind(this));
},
selectAllHandler: function() {
var checkboxes = $('.prospect_select_box');
console.log($(this)); // => [MyConstructor]
if (!$(this).prop('checked')) {
console.log('here')
checkboxes.prop('checked', false);
$('#prospect-left-section').hide();
} else {
console.log('other here')
checkboxes.prop('checked', true);
$('#prospect-left-section').show();
}
}
}
は、あなたが問題を示してHTMLと例の呼び出しを提供することができます?。 – trincot
@trincot上記のコードは、「私のコードは動作していません。」のところにあります。私のコードはどのように設定されていますか?今は違う唯一のことは、これは今のように呼ばれている: '$(document).on( 'click'、 '#my_element'、this.selectAllHandler.bind(this)); ' –
あなたの質問を読んだが十分な情報が含まれていません。 [this fiddle](https://jsfiddle.net/4pg8q7d6/) - >問題はありません。それで、あなたは何をやっているのですか? – trincot