James Lam
James Lam

Reputation: 1269

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?

Upvotes: 1

Views: 22

Answers (1)

Kit Sunde
Kit Sunde

Reputation: 37075

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);
});

Upvotes: 1

Related Questions