简体   繁体   中英

Javascript: How to call object method on Raphael path?

I have a JavaScript object that includes a number of Raphael paths. (The paths make up a stack of pie charts that all draw on the same paper.) I want each path to trigger an object method when clicked. However, when I click a path, I get "Uncaught TypeError: undefined is not a function" (Chrome for Mac OS). Does anyone know how to do this? Here's a distillation of my code:

// 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;
}

Teemu got it -- "this" in this context is the path, not the PieChartStack. Fixed by creating a new var: var self = this -- and then doing it like so:

self.handleSliceTap(chartIndex, sliceIndex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM