Javascript内存泄漏删除Raphael路径对象

时间:2012-10-05 12:45:15

标签: javascript memory-leaks raphael

我的代码中有内存泄漏,我无法弄清楚导致它的原因。我从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's Array.Remove未列出的函数和来自不同question的Raphael辅助函数

0 个答案:

没有答案