0

How can I bind this to a jQuery's event?

For instance, for the push menu below, I have to 'remember' this to var root:

class PushMenu {
    constructor() {
        this.slideShown = false;
        var root = this;
        $('.navmenu').on('shown.bs.offcanvas', function() {
            root.slideShown = true;
        });
    }
}

But I wonder if I can bind this so I can save having var root:

class PushMenu {
    constructor() {
        this.slideShown = false;
        $('.navmenu').on('shown.bs.offcanvas', function() {
            this.slideShown = true;
        });
    }
}

Is this possible?

Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

3

You are using es6 class so i assume es6 syntax are alright with arrow function

$('.navmenu').on('shown.bs.offcanvas', () => {
    this.slideShown = true;
});
Endless
  • 34,080
  • 13
  • 108
  • 131
2

Use jQuery.proxy()

Takes a function and returns a new one that will always have a particular context.

class PushMenu {
    constructor() {
        this.slideShown = false;
        $('.navmenu').on('shown.bs.offcanvas', jQuery.proxy(function() {
            this.slideShown = true;
        }, this));
    }
}

We could have used jQuery.proxy here so the reference to this refers to the object of PushMenu instead of the element that triggered the event.

Documentation

Community
  • 1
  • 1
Mohit Tanwani
  • 6,608
  • 2
  • 14
  • 32