user2031111
user2031111

Reputation:

this.transitionToRoute not working in my controller Ember

I am using a controller to read the value selected on a drop down menu, take in parameters of some input fields and then save the record. It creates the record and takes in the information just fine. My problem lies when I try to transition to another page at the end of the action. I keep getting the error: Cannot read property 'transitionToRoute' of undefined

I am completely stumped. Any ideas?

Here is my controller code:

var teamId;
export default Ember.Controller.extend({
    auth: Ember.inject.service(),
    actions: {
        onSelectEntityType: function(value) {
         console.log(value);
         teamId = value;
         return value;
      },
      createProcess: function(processName, processDescription) {
        var currentID = this.get('auth').getCurrentUser();
        let team = this.get('store').peekRecord('team', teamId);
        let user = this.get('store').peekRecord('user', currentID);
        let process = this.get('store').createRecord('process', {
            team: team,
            user: user,
            name: processName,
            description: processDescription
        });
        process.save().then(function () {
        this.transitionToRoute('teams', teamId);
      });
    }

    }
});

Here is the corresponding route:

export default Ember.Route.extend({
    auth: Ember.inject.service(),
    model: function() {
        var currentID = this.get('auth').getCurrentUser();
        return this.store.find('user', currentID);
    }
});

Upvotes: 0

Views: 2634

Answers (1)

Raj
Raj

Reputation: 342

You should have clear understanding about this keyword in Javascript. The keyword this only depends on how the function was called, not how/when/where it was defined.

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`

Have a look at the MDN documentation to learn more.

You can cache the this in normal variable this and then access inside the call back.

var self = this;

process.save().then(function () {
  self.transitionToRoute('teams', teamId);
});

ECMASCript 6 introduced arrow functions whose this is lexically scoped. Here, this is looked up in scope just like a normal variable.

process.save().then(() => {
  this.transitionToRoute('teams', teamId);
});

Upvotes: 4

Related Questions