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?

1
  • Try assigning this to a global variable and binding that variable instead. I am not sure if it will work. Commented Oct 9, 2016 at 9:29

2 Answers 2

3

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

$('.navmenu').on('shown.bs.offcanvas', () => {
    this.slideShown = true;
});
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for this answer. this is what I am after - ES6! thank you!! :-)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.