javascript - 从数组中删除函数

标签 javascript jquery arrays delegates

我有一个函数数组,我试图将它们用作 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/

相关文章:

javascript - 如何重新渲染 React 组件中已删除的子 DOM 元素?

html - 使用数据列表和 ajax 动态自动完成 HTML5 输入

java - 随机数组,不重复

c++ - 如何使用 "while loop "打印正确的输出?

javascript - 按钮单击音频启动和停止JS

javascript - SEQUELIZE 插入行时不会自动递增 id?

javascript - 有没有办法使用 HTML 通过 gmail 发送电子邮件

javascript - 为什么 tipsy 和 qtip 不选择我的 svg 元素?

javascript - 输入字段内的可点击图标

jquery - text/html 类型的 HTML 脚本 - 模板