0

I am working on backbone app. I am adding mousedown event using backbone which calls select function. Inside select function I am setting timeout which calls another function selection. In selection function I want to console currently clicked element using console.log(this.el). However, this.el is undefined because the this does not refer to my current module. How can I preserve this keyword so that I can use this in selection function?

Here is my code

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


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

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

    selection: function () {
        console.log(this.el);
    }
Om3ga
  • 30,465
  • 43
  • 141
  • 221

2 Answers2

2

Try:

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

Or:

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

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

Ian
  • 50,146
  • 13
  • 101
  • 111
2

You could solve it like this:

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

Many browsers also support the bind function, which binds an object as this to a function

select: function() {
    this.timeoutId = setTimeout(this.selection.bind(this), 1000);
}
NilsH
  • 13,705
  • 4
  • 41
  • 59