我的代码中有内存泄漏,我无法弄清楚是什么原因造成的。我从一个WebSocket
基本上包含一个 ID 和一个 X、Y 坐标的目标数据接收。数据被传递给一个HandleData
函数,该函数为每个目标创建一个圆圈和一条线(已更新)以显示目标从/到的移动位置。
如果目标不再出现在WebSocket
流中,则将其删除。在测试中,尽管我删除了这些项目,但我发现网页迅速积累了数百 mb 的数据。在使用 Chrome 的内存分析器时,尽管我删除了它,但 Raphael(或其他东西)似乎保留了所有路径信息。
如果有人可以帮助我,我将不胜感激。拉斐尔似乎确实掌握了数据,但我很有可能在代码中的某个地方犯了错误:)
var arrayColours = ["#f33", "#3f3", "#33f", "#f66", "#6f6", "#66f"];
var targetStructArray = [];
function HandleTargetData(data) {
//Go through all our existing targets and mark them as not updated
for (var i = 0; i < targetStructArray.length; i++) {
targetStructArray[i].updated = false;
}
for (var i = 0; i < data.targets.length; i++) {
var targetData = data.targets[i];
var targetStruct = undefined;
//find our targetStruct
for (var j = 0; j < targetStructArray.length; j++) {
if (targetStructArray[j].id == targetData.id) {
targetStruct = targetStructArray[j];
break;
}
}
//If it doesnt exist, create it
if (!targetStruct) {
var path = paper.path();
path.attr({ "stroke-width": "2", "stroke": "#888" });
path.addPart(['M', targetData.x, targetData.y]);
var circle = paper.circle(targetData.x, targetData.y, 15, 15).attr({
stroke: "none",
fill: arrayColours[Math.floor(Math.random() * arrayColours.length)] //random colour
});
//Create our struct
targetStruct = {
circle: circle,
path: path,
id: targetData.id,
updated: false
};
targetStructArray.push(targetStruct);
}
else {
targetStruct.circle.attr({ cx: targetData.x, cy: targetData.y });
targetStruct.path.addPart(['L', targetData.x, targetData.y]);
}
//ensure we are set as updated
targetStruct.updated = true;
}
//Go through all our existing targets and delete any that werent updated
for (var i = targetStructArray.length - 1; i >= 0; i--) {
if (!targetStructArray[i].updated) {
targetStructArray[i].circle.remove();
targetStructArray[i].path.remove();
targetStructArray[i].circle.removeData();
targetStructArray[i].path.removeData();
targetStructArray[i].circle = null;
targetStructArray[i].path = null;
targetStructArray[i] = null;
targetStructArray.remove(i);
}
}
}
我使用了此处未列出的两个函数,它们是John Resig 的 Array.Remove和来自不同问题的 Raphael 辅助函数