【问题标题】:Typescript this being overriden by jquery hover打字稿这被jQuery悬停覆盖
【发布时间】:2013-06-07 17:13:16
【问题描述】:

当您使用像$(".element").hover(functionHoverIn,functionHoverOut) 这样的jquery 悬停绑定时,jquery 似乎将悬停的元素传递为this。像这样:

$('.element').hover(function(e) { 
         $(this).attr("data-hovered", "true");
         //do whatever else
     }, function(e) {
         //etc
     }
}

它很有用,因此在这些匿名函数中,我们可以通过this$(this) 访问元素。 但是,它似乎与打字稿冲突。或者我有什么不明白的地方:

class FancyHover {
    HoverElement:JQuery;

    constructor(HoverElement:JQuery) {
        this.HoverElement = HoverElement;
        this.HoverElement.hover(this.HandleHover, this.HandleHover);
    }

    HandleHover(event:JQueryEventObject):void {
        $(event.currentTarget).toggleClass("hovered");

        this.OtherFunction(); //Throws error
        //Uncaught TypeError: Object #<HTMLDivElement> has no method 'OtherFunction' 
    }

    OtherFunction():void {
        //do anything
    }
}

理想情况下,我希望将一个函数(例如this.HandleHover)传递给.hover(functionIn,functionOut) 调用而不是匿名函数。但是,当我这样做时,我失去了引用当前 FancyHover 实例的能力。也许我可以以某种方式将当前实例传递给函数 HandleHover?

【问题讨论】:

标签: javascript jquery this typescript


【解决方案1】:

如果您想使用回调提供的this 以及类实例的this,则需要手动执行此操作,例如:

constructor() {
    // ...
    var self = this;
    this.HoverElement.hover(function(event) { self.HandleHover(event, this); });
}

HandleHover(event: JQueryEventObject, jqueryThis: JQuery) {
    $(jqueryThis).attr(/*etc*/);
    this.OtherFunction();
}

【讨论】:

  • 我想这可以解决问题。谢谢!虽然很丑。
  • 更新:this.HoverElement.hover(event =&gt; this.handlerover(event))this.handleElement.hover(this.handlehover.bind(this))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多