jQuery:从addEventListener切换到bind
原代码:jQuery:从addEventListener切换到bind,jquery,this,bind,addeventlistener,Jquery,This,Bind,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, th
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
?我不确定这是否回答了您的问题,但jQuery的自定义事件对象包含原始事件。它可以这样访问:e.originalEvent
其中e
是jQuery事件
另外,仅供参考,从jQuery 1.7开始,首选.on
方法而不是.bind
请参见:
即使使用代理,由于jQuery的自定义事件模型,此上下文也不再属于调用对象
我不认为jQuery的定制事件模型是这里的问题。代理回调函数时,此
值应引用包含控件
和其他属性(如ctime
和时间
的根对象,如原始示例所示
换句话说,不要试图从delegateTarget
var o = e.delegateTarget;
o.time.hashours = (o.duration() / 3600) >= 1.0;
...
但只要坚持你的原始代码
this.time.hashours = (this.duration() / 3600) >= 1.0;
签出与您的结构相似的最小值。如果要在
事件处理程序中使用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
});
当我使用var o=e.originalEvent时代码>,o.time
未定义。说得好。我认为@Anurag的答案更符合你的要求。你是对的。使用.on
而不是.bind
与$代理一起工作。谢谢@BrianGraham-bind
和on
在这个特定示例中没有任何功能差异。可能是其他原因导致了这些错误。