我在处理时间事件时总是遇到困难。有人能解释一下为什么A不起作用而B起作用吗?唯一的区别是在 A 中我将事件绑定(bind)放在一个函数中。不用担心函数关闭,它与问题无关。当我测试A时,没有js错误,但计时器没有清除。
A->
Test.Navigation = (function() {
var openTimer = null;
var closeTimer = null;
var addListeners = function() {
$('.hover_container').on('mousemove', function(e) {
clearTimeout(closeTimer);
});
$('.hover_container').on('mouseleave', function(e) {
// set the close timer
var container = this;
closeTimer = setTimeout(function() {
//has the mouse paused
close(container);
}, 750);
});
};
return {
init : function() {
addListeners();
}
};
})();
B->
Test.Navigation = (function() {
var openTimer = null;
var closeTimer = null;
$('.hover_container').on('mousemove', function(e) {
clearTimeout(closeTimer);
});
$('.hover_container').on('mouseleave', function(e) {
// set the close timer
var container = this;
closeTimer = setTimeout(function() {
//has the mouse paused
close(container);
}, 750);
});
var addListeners = function() {
// nothing here
};
return {
init : function() {
addListeners();
}
};
})();
编辑:请忽略容器部分,它与问题无关,它只是我没有取出的完整代码的一部分
最佳答案
A 在调用 init 的对象存在之前绑定(bind)。因为你返回一个新对象。如果您正在使用,则会创建 2 个对象。 1 与 vars en 绑定(bind)。和 1 与返回。
B 正在工作,因为您创建了一个函数,其中元素被初始化并使用正确的范围。 A 不起作用,因为绑定(bind)位于错误的范围内,因为您创建了 2 个对象:
new Test.Navigation(); // Create 1 object
// Create second object.
return {
init : function() {
addListeners();
}
};
你最好得到这样的结构,那么它应该也能工作:
Test.Navigation = (function() {
// Private vars. Use underscore to make it easy for yourself so they are private.
var _openTimer = null,
_closeTimer = null;
$('.hover_container').on('mousemove', function(e) {
clearTimeout(_closeTimer );
});
$('.hover_container').on('mouseleave', function(e) {
// set the close timer,
// use $.proxy so you don't need to create a exta var for the container.
_closeTimer = setTimeout(
$.proxy(function() {
//has the mouse paused
close(this);
}, this)
, 750);
});
this.addListeners = function() {
// nothing here
};
this.init = function() {
this.addListeners();
}
// Always call the init?
this.init();
return this; // Return the new object Test.Navigation
})();
并像这样使用它
var nav = new Test.Navigation();
nav.init();
正如您所看到的,我对您的代码进行了一些升级。使用 $.proxy
、_
作为私有(private)变量。
关于javascript时间事件问题(setTimeout/clearTimeout),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12922106/