我需要在socket.io事件中使用从前端传递的不同变量创建同一函数的多个实例。我还需要这些变量对另一个socket.io事件可见,以便我可以从前端单击停止该功能。我的一切都很好,但我只能用一个带变量的实例' bigLoop'并需要它为多个实例工作。我需要所有的循环能够运行并且彼此独立。
套接字事件:
//this is what I have so far and it works great, I can start and stop at any time. And I know bigLoop is global
io.on('connection', function(connect) {
//create new loop
connect.on('createLoop', function(data) {
bigLoop = new syncLoop(data.total, function(){}, function(){});
});
//end loop
connect.on('endLoop', function(data) {
bigLoop.break(true);
});
});
//this is what I would like passing an array of multiple variables from the front end and creating a new syncLoop for each variable
//create new loop
connect.on('createLoop', function(data) {
//save array to variable
var newNames = data.array;
//for each variable create new syncLoop
newNames.forEach(function(newLoops) {
newloops = new syncLoop(data.total, function(){}, function() {});
});
});
//end loop
connect.on('endLoop', function(data) {
//save array to variable
var endNames = data.array;
//for each variable end loop
endNames.forEach(function(endLoops){
endLoops.break(true);
});
});
//syncLoop function, for process and exit I have a lot more going on but did not want to write it
function syncLoop(iterations, process, exit){
var index = 0,
done = false,
shouldExit = false;
loop = {
next:function(){
if(done){
if(shouldExit && exit){
return exit(); // Exit if we're done
}
}
// If we're not finished
if(index < iterations){
index++; // Increment our index
process(loop); // Run our process, pass in the loop
// Otherwise we're done
} else {
done = true; // Make sure we say we're done
if(exit) exit(); // Call the callback on exit
}
},
iteration:function(){
return index - 1; // Return the loop number we're on
},
break:function(end){
done = true; // End the loop
shouldExit = end; // Passing end as true means we still call the exit callback
}
};
loop.next();
return loop;
};
&#13;
我尝试了很多不同的东西,但是我无法让它发挥作用。我感谢任何帮助。谢谢。
答案 0 :(得分:0)
如果我理解你的问题:
尝试创建所有正在运行的循环的全局映射:
// global variable
var loops = {};
function createLoop(name, data) {
stopLoop(name);
loops[name] = new syncloop(/*...*/);
}
function stopLoop(name) {
if (loops[name]) {
loops[name].break(true);
delete loops[name]; // remove entry from map
}
}
变量loops
将按名称包含所有当前运行的循环。