Search code examples
javascriptember.jsbootstrap-switch

EmberJS Using Component in Different Context


I am trying to use a different library bootstrap-switch from within EmberJS.

I added the following with .on('didInsertElement'):

$(toggleTag).on('switchChange.bootstrapSwitch', function(event, state) {
      this.sendAction('updateAction', state);
});

However, when this event is invoked, the context of this will return object for the html element toggleTag. Instead, I need access to the component for this.

What is the recommended way of dealing with this issue?


Solution

  • In ES6 use fat arrows and inherit the context of the parent (if you're using ember-cli, this is recomended):

    $(toggleTag).on('switchChange.bootstrapSwitch', (event, state) => {
      this.sendAction('updateAction', state);
    });
    

    In ES5 either use bind to fix the function context:

    $(toggleTag).on('switchChange.bootstrapSwitch', function(event, state){
      this.sendAction('updateAction', state);
    }.bind(this));
    

    Or save the context:

    var that = this;
    $(toggleTag).on('switchChange.bootstrapSwitch', function(event, state){
      that.sendAction('updateAction', state);
    });