我在使用 .delegate()
的处理程序回调方面遇到了一些问题在 jQuery 中。此设置使用 2 个文件 - 在创建 $B 的位置,另一个是简单的 $(doc).ready 文件。
我有一个 SVG 文件,其中有一堆 (50+) <g>
当我点击、滚动、滚动等时我需要跟踪的标签。而不是将功能附加到 <g>
节点,委托(delegate)看起来更简洁。
但是,我遇到了一个问题,我认为我对 JavaScript 的了解相对不足。
这是我的主要 ready() 文件的设置:
$C.Events.onStation({
click : function(e){
console.log(e)
return false;
},
mouseenter : function(e){
return false;
},
mouseleave : function(e){
return false;
}
})
这很好用。一切都通过了,等等。在我的 $B.Events 对象中:
Events : new function(){
var _station = function(obj){
// delegate the events to the primary SVG node
for(var type in obj){
$(City.Map.node).delegate('g', type, function(){
obj[type]()
})
}
return {
onStation : _station
}
// others taken out for relevance
}()
现在,有了这个,如果我传入 obj[type]
而不是将它包装在另一个函数中,它工作正常。唯一的问题是我需要对传入的函数做一些准备工作(即弄乱事件数据对象)以及移动所有 return false
进入委托(delegate)代码,而不是弄乱我的其他文件。
那么我怎样才能从 jQuery 的 .delegate()
的回调处理函数中执行的第一个代码块中获取函数呢?功能?
在响应中编辑
我认为这是朝着正确方向迈出的一步。我有一种感觉,它与 JS 的性质有关,而不一定是逻辑。这就是我有时讨厌 Javascript 的原因。
此解决方案的问题在于它将原语传递给通用构建器函数。我需要存储并返回一个可执行函数。我尝试过的几件事都没有成功。这是我尝试过的许多事情的一个例子:
var _station = function(events){
var _funcs = {}
var _selection = null;
var create = function(f){
return function(){ return f() }
}
for(var t in events){
_funcs[t] = create(t, events[t])
}
console.log(_funcs)
// delegate the events to the primary SVG node
for(var type in events){
$('#stations', Bart.Map.node).delegate('g', type, function(e){
_funcs[type](e)
e.stopPropagation()
})
}
}
当我 log(_funcs[type])
它作为一个函数返回,但我无法终生执行它。
这个关闭的东西让我很生气。
最佳答案
您在生成闭包和循环时仍然遇到问题。您可以将 type
作为事件数据传递:
var $target = $('#stations', Bart.Map.node); // capturing is a good idea
for(var type in events){
$target.on(type, 'g', {type: type}, function(e){
_funcs[e.data.type](e);
e.stopPropagation();
})
}
或者您可以使用 jQuery.each
遍历 events
:
$.each(events, function(type) {
$target.on(type, 'g', function(e){
_funcs[type](e);
e.stopPropagation();
});
});
重要的一点是每个闭包(事件处理程序)都可以访问它自己的 type
变量。
请注意,我使用 .on()
而不是 .delegate()
,这是自 jQuery 1.7 以来的首选。
关于javascript - jQuery 委托(delegate)回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8801478/