Javascript:如何在Raphael路径上调用对象方法?

时间:2014-09-05 21:23:18

标签: javascript raphael

我有一个JavaScript对象,其中包含许多Raphael路径。 (路径组成了一堆饼图,所有饼图都在同一张纸上绘制。)我希望每个路径在单击时触发对象方法。但是,当我单击一个路径时,我得到“Uncaught TypeError:undefined is not a function”(适用于Mac OS的Chrome)。有谁知道如何做到这一点?这是我的代码的精华:

// Definition of PieChartStack object
function PieChartStack() {

    this.setNodeTree = function (nodeTree) {
        this.nodeTree = nodeTree;
        ...
        this.performInitialSetup();
    }

    this.performInitialSetup = function() {
        ...
        var paper = Raphael("holder", "100%", "100%");
        ...
        paper.customAttributes.segment = function (x, y, r, a1, a2) {
            ...
            return {
                path: [["M", x, y], ["l", r * Math.cos(a1), r * Math.sin(a1)], ["A", r, r, 0, +flag, 1, x + r * Math.cos(a2), y + r * Math.sin(a2)], ["z"]],
                fill: "hsb(" + clr + ", .75, .8)"
            };
        };

        this.handleSliceTap = function(chartIndex, sliceIndex) {
            console.log(chartIndex + " , " + sliceIndex);
        }

        for (var chartIndex = 0; chartIndex < this.pieCharts.length; chartIndex++) {
            ...
            for (sliceIndex = 0; sliceIndex < sliceCount; sliceIndex++) {
                ...
                var path = paper.path().attr({segment: [this.centerX, this.centerY, 1, start, start + val], stroke: "#fff"});

                // PROBLEM HERE ======================================
                path.click(
                    function (e) {
                        this.handleSliceTap(chartIndex, sliceIndex);
                    }
                );
                //====================================================
            }
        }
    }
    return this;
}

1 个答案:

答案 0 :(得分:1)

Teemu得到了它 - 在这个上下文中的“this”是路径,而不是PieChartStack。修复了通过创建一个新的var:var self = this - 然后这样做:

self.handleSliceTap(chartIndex, sliceIndex);