【问题标题】:JS method binding with 2 different thisJS 方法绑定 2 个不同的 this
【发布时间】:2015-01-28 13:58:36
【问题描述】:

我有这个小代码:

ScenesController.prototype.viewAction = function() {
    this.flash = this.di.HelperFlash.hasSupport();

    this.$playerElem = !this.flash? $('#html_player') : $('#flash_player');
// the first click is just a sample, I need the same object in the Quailty Change method
    $('.scenes_view_video_quailty').on('click', function() { echo($(this));});
    $('.scenes_view_video_quailty').on('click', this.viewVideoQuailtyChange.bind(this));

};
ScenesController.prototype.viewVideoQuailtyChange = function(e) {
    e.preventDefault();
    if (!this.flash) {
        echo(this);
        echo($(this));
    }
};

当我单击链接时,我需要将此变量传递给 QualityChange 方法 2。一个是对象(在绑定中),另一个是点击事件,因为我也需要点击的元素。

我正在尝试使用 .on('click', {$this: $(this)}, this.method) 解决方案,但不起作用,eventd.data.$this 看起来是一个不同的对象。

我需要与第一次单击方法中相同的对象。 (echo = console.log)

【问题讨论】:

  • 只需在事件处理程序中使用e.currentTarget 来获取点击的元素。
  • 哦,这是我当前问题的解决方案:D 但不是我问题的答案,我想在非匿名方法中拥有完整的对象。谢谢顺便说一句,好主意! :)
  • 是的,我需要 QualityChange 方法中的完整 $(this),但它是不同的范围,这是 viewAction,但我想访问与匿名方法中相同的 this(我的示例中的第一个点击行)

标签: javascript jquery oop


【解决方案1】:

别名 this 将当前实例称为其他东西(传统上,self)并使用 this 来引用单击的元素

ScenesController.prototype.viewAction = function() {
    var self = this;
    this.flash = this.di.HelperFlash.hasSupport();

    this.$playerElem = !this.flash? $('#html_player') : $('#flash_player');

    $('.scenes_view_video_quailty').on('click', function() { echo(self, $(this));});    
};

要调用设置为this 引用的方法,您可以使用Function.apply,例如:

$('.scenes_view_video_quailty').on('click', function(){
         self.viewVideoQuailtyChange.apply(self, [$(this)])
});

【讨论】:

  • 我的问题是另一个点击,我需要将这两个都传递给 QualityChange 方法。点击这个和这个对象也是。
  • 好主意,但还是不行- [对象[对象 { di={...}, flash=false, $playerElem={...}, több...}]] getjs (2386. sor) -------- 对象 { originalEvent=Event click, type="click", timeStamp=441803473, több...} 只有第一个看起来是真正的 jQ 对象
  • @KrizsánBalazs 我认为你错过了重点,在被调用的方法this 现在将引用对象实例,传入的单个参数是 jQ 对象。 (例如,在您的方法中执行 console.log(this)console.log(e)。第一个将是实例,第二个是 jQuery 对象
  • 是的,也许我不明白这一点,但如果没有 $(),log(this) 和 log(e) 将是相同的对象,我在控制台中看到。但我需要我在匿名函数中拥有的 jQ 对象(在第一次点击事件中)。
  • 我很接近,如果我先应用 2 this,然后单击 click 事件,我将同时拥有 this 但由于应用程序在调用后立即运行该方法。 :\
【解决方案2】:

您可以使用bind 附加任意数量的变量 你可以有一个合适的方法,比如:

ScenesController.prototype.viewVideoQuailtyChange = function(secondThis) {
}

然后使用绑定为:

this.viewVideoQuailtyChange.bind(this, $(this));

使用此解决方案,您确实会丢失事件,因此可能需要更多考虑。我会调查并更新答案:)

【讨论】:

  • 不行,因为this作用域是一样的,唯一不同的是,最后一个是jQ对象。
猜你喜欢
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
  • 2015-10-01
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
相关资源
最近更新 更多