我有一个函数数组,我试图将它们用作 c# 中的委托(delegate)事件。
我将一个函数推送到数组,当数组循环遍历函数时,它将被调用。
问题是我在使用完该功能后无法删除该功能,这违背了目的。
这是我的代码。我完全准备采用不同的方法来做到这一点,我对 JS/JQ 相当陌生,所以这就是我想出的方法。
var MouseMoveFunctions = [];
$(document).ready(function(){
//Create the event to call our functions.
$(document).mousemove(function(e){
CallMouseMoveFunctions(e);
});
});
function CallMouseMoveFunctions(e){
//Only continue if there is atleast 1 function in the array.
if(MouseMoveFunctions.length == 0) return;
//Call each function in the array.
for(var i = 0; i < MouseMoveFunctions.length;i++){
MouseMoveFunctions[i](e);
}
}
$(document).ready(function(){
//Add the TrackMouse function to the array.
MouseMoveFunctions.push(function(event){TrackMouse(event)});
});
var mX = 0;
var mY = 0;
function TrackMouse(e){
mX = e.pageX;
mY = e.pageY;
var index = MouseMoveFunctions.indexOf(function(event){TrackMouse(event)});
alert(index); //Always coming up -1, so it isn't getting removed
//Try and remove the function if it exists, just for now so I know its working
if(index != -1){
MouseMoveFunctions.splice(index);
}
}
最佳答案
//Always coming up -1, so it isn't getting removed
你总是得到-1
,因为你将一个唯一的函数对象传递给.indexOf()
,所以它不可能已经在数组中。您插入数组的匿名函数没有其他引用,因此您无法通过引用将其删除。
因为您要推送和删除一个仅传递事件参数的函数,所以您可以推送该函数本身。
MouseMoveFunctions.push(TrackMouse);
然后通过身份查找相同的函数就可以成功找到它。
var index = MouseMoveFunctions.indexOf(TrackMouse);
请注意,如果您将同一函数多次放入数组中,则每次都需要单独删除它。
此外,正如 Scott 所说,您需要提供要删除的项目数量。
<小时/>更好的解决方案是使用Set
而不是数组。另外,您可以摆脱那些 .ready()
处理程序。
var MouseMoveFunctions = new Set();
//Create the event to call our functions.
$(document).mousemove(CallMouseMoveFunctions);
function CallMouseMoveFunctions(e){
//Only continue if there is atleast 1 function in the array.
if(MouseMoveFunctions.size == 0) return;
//Call each function in the set.
for(const fn of MouseMoveFunctions) {
fn(e);
}
}
//Add the TrackMouse function to the array.
MouseMoveFunctions.add(TrackMouse);
var mX = 0;
var mY = 0;
function TrackMouse(e){
mX = e.pageX;
mY = e.pageY;
MouseMoveFunctions.delete(TrackMouse);
}
关于javascript - 从数组中删除函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48727370/