0

This is a small chunk of my code. The problem is about this. The code below "this" refers to HomeView class because I did this._changeLanguage.bind(this). If I remove the bind(this) part then this refers to li element but then I cannot call this._renderHTML() method.

class HomeView extends BaseView{

    constructor(model){
        super(null, model);
    }

    _renderHTML(){
        this.$view.html(template(this.model));
        return this.$view;
    }

    _init(){
        this.$view.on("click", "#langs li", this._changeLanguage.bind(this));
    }

    _changeLanguage(){
        console.log($(this).data("lang"));
        this._renderHTML();
    }

}

What is the cleanest approach to run _changeLanguage method on a click event like this.

Barış Velioğlu
  • 5,709
  • 15
  • 59
  • 105

1 Answers1

-1

You should be able to write your _changeLanguage() method as such: class HomeView extends BaseView {

    _changeLanguage = () => {
        console.log($(this).data("lang"));
        this._renderHTML();
    };
}

The fat-arrow syntax gives you implicit binding on this, so you can change your other code to:

_init(){
    this.$view.on("click", "#langs li", this._changeLanguage);
}

Therefore no more bind()... it's all implicit thanks to ES6.

arthurakay
  • 5,631
  • 8
  • 37
  • 62