Есть ли способ передать контекст для привязки в jQuery?
Я внутри объекта javascript (vr roxx:)), но каждый раз, когда я связываю событие с jQuery, я должен включать контекст экземпляра основного объекта через параметр данных, чтобы работать с ним. Не существует ли простой/опрятный способ сделать это в jQuery?
var oink =
{
pig: null,
options:
{
showPigMom: 0
},
init: function(pigObj)
{
//Show the pigmom
$(this.doc).bind('keyup click', {o: this}, function(e)
{
var o = e.data.o;
if (o.options.showpath)
o.doWhatever();
});
...
Ответы
Ответ 1
Я использую $.proxy()
функцию
init: function(pigObj)
{
//Show the pigmom
$(this.doc).bind('keyup click', $.proxy(function(e) {
if (this.options.showpath)
this.doWhatever();
$(e.currentTarget).text(); // use this to access the clicked element
}, this));
}
Ответ 2
init: function() {
var self = this;
$(this.doc).bind('keyup click', function() {
if (self.options.showpath) self.doWhatever();
});
}
Ответ 3
init: function() {
$(this.doc).bind('keyup click', function() {
if (this.options.showpath) this.doWhatever();
$(e.currentTarget).text(); // use this to access the clicked element
}.bind(this))
}