2012-01-17 47 views
0

原始代码:jQuery的:从的addEventListener切换到绑定

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)); 

即使有代理,这样的背景下已经不再属于由于jQuery的自定义事件模型而调用对象。我怎样才能得到原来的this.control

回答

2

即使有代理,这样的背景下已经不再属于因为jQuery的自定义的调用对象事件模型。

我不认为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类似于你的结构。

+1

你说得对。使用'.on'代替'.bind'可以使用'$ .proxy',谢谢! – 2012-01-17 20:34:00

+0

@BrianGraham - 'bind'和'on'在这个特定的例子中没有任何功能上的区别。这可能是导致错误的其他原因。 – Anurag 2012-01-18 01:42:27

0

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

此外,仅供参考,在jQuery 1.7中,.on方法优于.bind见:http://api.jquery.com/bind/

+0

当我使用'var o = e.originalEvent;'时,'o.time'是未定义的。 – 2012-01-17 20:25:03

+0

好点。我认为@ Anurag的答案更符合你的需求。 – 2012-01-17 20:33:18

0

如果你想在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 
});