0

我正在开发骨干应用程序。我正在使用调用函数的mousedown主干添加事件。我正在设置的select内部函数调用另一个函数。在功能中,我想使用. 但是,未定义,因为 this 不引用我当前的模块。我怎样才能保留这个关键字,以便我可以在选择功能中使用它?selecttimeoutselectionselectioncurrently clicked elementconsole.log(this.el)this.el

这是我的代码

    events: {
        'mousedown': 'select',
        'mouseup': 'deselect'
    },


    select: function () {
        this.timeoutId = setTimeout(this.selection, 1000);
    },

    deselect: function () {
        clearTimeout(this.timeoutId);
    },

    selection: function () {
        console.log(this.el);
    }
4

2 回答 2

2

尝试:

var self = this;
self.timeoutId = setTimeout(function () {
    self.selection();
}, 1000);

或者:

this.timeoutId = setTimeout(this.selection.bind(this), 1000);

参考 - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind

于 2013-04-23T06:20:53.107 回答
2

你可以这样解决它:

select: function() {
    var self = this;
    this.timeoutId = setTimeout(function() {
        self.selection();
    }, 1000);
}

许多浏览器也支持bind函数,它将对象绑定this到函数

select: function() {
    this.timeoutId = setTimeout(this.selection.bind(this), 1000);
}
于 2013-04-23T06:22:29.643 回答