/ / jquery "this"イベントハンドラのバインディングの問題(prototypeのbindAsEventListenerに相当) - javascript、jquery、events、binding、this

jquery "この"イベントハンドラのバインディングの問題(prototypeのbindAsEventListenerに相当) - javascript、jquery、events、binding、this

jqueryでは、イベントhadlerのバインディングはDOM要素を生成するイベントです(これはdom要素を指します)。 イベントハンドラのバインディングを変更するプロトタイプでは、 bindAsEventListener 関数; イベントハンドラからインスタンスとDOM要素の両方にアクセスするにはどうすればよいですか?
に似ている イベントハンドラをJQueryのインスタンスにバインドするにはどうすればよいですか?

function Car(){
this.km = 0;
$("#sprint").click(this.drive); //setup event handler
}

// event handler
// in it I need to access both the clicked element
// and the binding object (instance of car)
Car.prototype.drive = function(){
this.km += 10; // i"d like to access the binding (but jq changes it)
this.css({ // also the element
left: this.km
});
// NOTE that is inside this function I want to access them not elsewhere
}

var car = new Car();

回答:

回答№1は4

うーん、おそらくあなたはjQuery.proxy()を使うことができますか?

http://api.jquery.com/jQuery.proxy/


回答№2の場合は1

変数をバインドするだけです this それを使用してください。

function Car(){
this.km = 0;
var that = this;
$("#sprint").click(function(){
that.drive(this);
});
}


Car.prototype.drive = function(element){
this.km += 10; // i"d like to access the binding (but jq changes it)
this.css({ // also the element
left: this.km
});
alert(element.innerHTML);
// NOTE that is inside this function I want to access them not elsewhere
}

ハンドラは要素をインスタンスに渡します。


回答№3の場合は0

this そうでなければポイントする(つまり、ハンドラがアタッチされている要素)も currentTarget イベントオブジェクトのプロパティ。したがって、あなたが話したバインディング関数を使用する場合は、

Car.prototype.drive = function(e) {
// this will be your car object
// e.currentTarget will be the element that you attached the click handler to
}

回答№4の場合は0

はい、どうぞ :

var car = {km:0};
$("#sprint").click(function(){
car.km += 10;
$(this).css({ left: car.km });
});

私はそれをテストしていないが、まっすぐ進むべきであるか、またはどこに間違っていたかは、 "車"オブジェクトではなく "スプリント"要素を見ているあなたの "これ"にある。