【问题标题】:jQuery: Switching from addEventListener to bindjQuery:从 addEventListener 切换到绑定
【发布时间】:2012-01-17 20:13:24
【问题描述】:

原代码:

this.control.addEventListener('click', $.proxy(function() {
    this.time.hashours = (this.duration() / 3600) >= 1.0;
    this.time.duration.text(getTime(this.duration(), this.controls.time.hasHours));
    this.time.current.text(getTime(0, this.controls.time.hasHours));
}, this));

跨浏览器支持的尝试:

$(this.control).bind('click', $.proxy(function(e) {
    var o = e.delegateTarget;
    o.time.hashours = (o.duration() / 3600) >= 1.0;
    o.time.duration.text(getTime(o.duration(), o.controls.time.hasHours));
    o.time.current.text(getTime(0, o.controls.time.hasHours));
}, this));

即使使用代理,this 的上下文也不再属于调用对象,因为 jQuery 的自定义事件模型。如何获取原始this.control

【问题讨论】:

    标签: jquery this bind addeventlistener


    【解决方案1】:

    即使使用代理,由于 jQuery 的自定义事件模型,this 的上下文不再属于调用对象。

    我不认为 jQuery 的自定义事件模型是这里的问题。当您代理回调函数时,this 值应引用包含 control 和其他属性(如 ctimetime)的根对象,如原始示例中所示。

    也就是说,不要试图从delegateTarget获取这样的原始对象

    var o = e.delegateTarget;
    o.time.hashours = (o.duration() / 3600) >= 1.0;
    ...
    

    但只要坚持你的原始代码,

    this.time.hashours = (this.duration() / 3600) >= 1.0;
    

    查看这个与您的结构相似的最小 example

    【讨论】:

    • 你是对的。使用 .on 而不是 .bind$.proxy 一起使用,谢谢!
    • @BrianGraham - bindon 在此特定示例中没有任何功能差异。可能是其他原因导致了错误。
    【解决方案2】:

    我不确定这是否能回答您的问题,但 jQuery 的自定义事件对象包含原始事件。它可以像这样访问:e.originalEvent 其中e 是 jQuery 事件。

    另外,仅供参考,从 jQuery 1.7 开始,.on 方法优于 .bind,请参阅:http://api.jquery.com/bind/

    【讨论】:

    • 当我使用var o = e.originalEvent;时,o.time是未定义的。
    • 好点。我认为@Anurag 的答案更符合您的要求。
    【解决方案3】:

    如果你想在click 事件处理程序中使用this.control,那么你应该这样做。

    var $context = this;
    $(this.control).bind('click', function(e) {
        //You can use $context here
        //var o = e.delegateTarget;
        $context.time.hashours = ($context.duration() / 3600) >= 1.0;
        $context.time.duration
        .text(getTime($context.duration(), $context.controls.time.hasHours));
        $context.time.current.text(getTime(0, $context.controls.time.hasHours));
    
        //And this will point to this.control on which the event is triggered
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多