【发布时间】:2018-02-11 01:30:09
【问题描述】:
我有一个函数数组,我正在尝试像 c# 中的委托事件一样使用它们。
我将一个函数推送到数组中,当数组循环遍历函数时,它将被调用。
问题是我在完成后无法删除该功能,这有悖于目的。
这是我的代码。我完全愿意用不同的方法来做这件事,我对 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);
}
}
【问题讨论】:
标签: javascript jquery arrays delegates