Skip to content

Instantly share code, notes, and snippets.

@joeylin
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save joeylin/9638144 to your computer and use it in GitHub Desktop.

Select an option

Save joeylin/9638144 to your computer and use it in GitHub Desktop.
focus事件绑定的坑和带后缀事件的绑定解绑
marker.$element.on('focus', function() {
$doc.on('keydown.' + marker._id, function(e) {
var key = e.keyCode || e.which;
if (key === 46) {
self.del(marker);
}
});
}).on('blur', function() {
$doc.off('keydown.' + marker._id);
});
这种写法的问题是聚焦的时候重复点击,会再次触发focus事件,
这时候就造成了重复绑定的问题。
目前的解决方法:在marker上面保存一个flag来手工标示,防止重复绑定。
marker.hasBinded = false;
marker.$element.on('focus', function() {
if (!marker.hasBinded) {
$doc.on('keydown.' + marker._id, function(e) {
var key = e.keyCode || e.which;
if (key === 46) {
self.del(marker);
}
});
marker.hasBinded = true;
}
}).on('blur', function() {
$doc.off('keydown.' + marker._id);
marker.hasBinded = false;
});
使用one可以自动只执行一次,但是还是会多次绑定。
因此从focus的角度使用one,
var callback = function() {
$doc.on('keydown.' + marker._id, function(e) {
var key = e.keyCode || e.which;
if (key === 46) {
self.del(marker);
}
});
};
marker.$element.one('focus', callback).on('blur', function() {
$doc.off('keydown.' + marker._id);
marker.$element.one('focus',callback);
});
1, 理清带后缀事件的绑定与解绑
四个绑定到document的keydown事件:keydown.1 keydown.2 keydown.3 keydown.4
触发一次keydown事件,上面四个事件会同时触发
使用.off('keydown'),会使上面四个事件同时解绑
使用.off('keydown.1'),解绑keydown.1事件
2, mousedown事件阻止focus事件的发生
focus事件是在冒泡到document之后再返回到原来的元素上面才被触发,
因此在在mousedown事件中使用return false 被阻止focuse事件的触发
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment