0

I created a class to manage the main UI interactions with my app. In the constructor, I'd like to wire up the click event for the nav li's. Can someone help me figure out how to scope these objects correctly?

class app {
    constructor() {

        $('.nav li').on("click", function() {
            //  I want to call changeView but pass in the data attribute from the li as the view param
            //  ex.  changeView($(this).data('view'));
        });

    }

    changeView(view) {
        console.log(view);
    }
}
dhysong
  • 1,011
  • 1
  • 14
  • 29
  • The problem is no different in ES6 than it was in ES5. – Bergi Jan 12 '16 at 21:38
  • The problem is the same, but the solutions are different now that we have the arrow function. We now have an elegant solution to the "this" scope issue. – dhysong Jan 12 '16 at 21:46

2 Answers2

3

Use an arrow function:

$('.nav li').on("click", e => {
    this.changeView($(e.target).data('view'));
});
Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28
0

I believe this will work if you use ES6 arrow functions

class app {
    constructor() {
        $('.nav li').on("click", () => {
            //  I want to call changeView but pass in the data attribute from the li as the view param
            this.changeView($(this).data('view'));
        });
    }

    changeView(view) {
        console.log(view);
    }
}
searsaw
  • 3,492
  • 24
  • 31