Method of object as handler

*爱你&永不变心* 提交于 2019-12-12 04:53:14

问题


I try this:

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

MovableLine.prototype.start = function (e) {

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

and then:

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);

result:
first alert: undefined
second alert: object SWGPathElement

How to get my object movableLine from start()?


回答1:


I would recommand to not use prototype for event methods. Assign the function as an object property and also, cache the this reference :

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

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

Alternatively, you can use a click catcher if you absolutely want to use .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);


来源:https://stackoverflow.com/questions/26550876/method-of-object-as-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!