/ / jQuery зв'язується з іншим цим - javascript, jquery

jQuery зв'язується з іншим - javascript, jquery

Я хочу пов'язати функцію з подією, але я хочу змінити контекст, в якому викликається ця функція

function Foo(){

t : "123",
bar: function(){
// I am here
$("#selector").bind("click" this.foo);
}
,
foo: function(){
//I want when to be able to use the current object here by this
//this.t should be 123 and this.bar should call the above function
}
}

Відповіді:

5 за відповідь № 1

Ви можете використовувати jQuery.proxy:

$("#selector").bind("click", $.proxy(this.foo,this) );

1 для відповіді № 2

Скопіюйте посилання на об'єкт до локальної змінної та використовуйте його в функції:

var me = this;
$("#selector").bind("click" function() { me.foo(); });

Якщо вам потрібен об'єкт події, передайте це на:

var me = this;
$("#selector").bind("click" function(e) { me.foo(e); });