【问题标题】:Javascript: How to call object method on Raphael path?Javascript:如何在 Raphael 路径上调用对象方法?
【发布时间】:2014-09-06 09:51:19
【问题描述】:

我有一个包含多个 Raphael 路径的 JavaScript 对象。 (这些路径组成了一堆饼图,它们都绘制在同一张纸上。)我希望每条路径在单击时触发一个对象方法。但是,当我单击路径时,我得到“未捕获的类型错误:未定义不是函数”(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;
}

【问题讨论】:

  • this 在点击处理程序中并不是你想象的那样。 console.log(this) 在那个函数中会清除你的东西。
  • 在调用 click 处理程序时,chartIndexsliceIndex 都将超出范围。我假设错误发生在handleSliceTap() 中,当它尝试对这些索引执行任何操作时。
  • Teemu,你搞定了——这里的“this”是路径,而不是 PieChartStack。谢谢!

标签: javascript raphael


【解决方案1】:

Teemu 明白了——这里的“this”是路径,而不是 PieChartStack。通过创建一个新的 var 来修复: var self = this -- 然后这样做:

self.handleSliceTap(chartIndex, sliceIndex);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2015-02-20
    相关资源
    最近更新 更多