对象的方法作为处理程序

时间:2014-10-24 15:12:23

标签: jquery highcharts jquery-on

我试试这个:

function MovableLine (line, number) {
    this.line = line;
    this.number = number;
}

MovableLine.prototype.start = function (e) {

    alert(this.number);
    alert(this);
};

然后:

var mline = this.xAxis[0].plotLinesAndBands[plotLinesCount].svgElem;
                mline.css({
                    'cursor': 'pointer'
                });
                mline.translate(0, 0);
                movableLine = new MovableLine(mline, 10);
                movableLine.line.on('mousedown', movableLines[plotLinesCount].start);

结果:
第一次警报:未定义
第二个警告:对象SWGPathElement

如何从start()获取我的对象movableLine?

1 个答案:

答案 0 :(得分:0)

我建议不要将原型用于事件方法。将该函数指定为对象属性,并缓存this引用:

function MovableLine (line, number) {
    var self = this; //Caching
    this.line = line;
    this.number = number;
    this.start = function (e) {

        alert(self.number);
        alert(self);
    };
}

或者,如果您绝对想要使用.prototype

,则可以使用点击捕手
function MovableLine (line, number) {
    var self = this; //Caching
    this.line = line;
    this.number = number;
    this.clickCatcher = function () {
        self.start.apply(self, Array.prototype.slice.call(arguments, 0));
    };
}

MovableLine.prototype.start = function (e) {

    alert(this.number);
    alert(this);
};

//And you event binding:
movableLine.line.on('mousedown', movableLines[plotLinesCount].clickCatcher);