ember.jstorii

"this" is undefined in torii-adapter in ember


I am trying to store some data post login inside store. Below is code of my torii-adapter

import Ember from 'ember';
import {createToken} from 'myapp/utils/app-utils';

export default Ember.Object.extend({
  store: Ember.inject.service(),

  open: function(authentication){
    let authorizationCode = authentication.authorizationCode;
    let token = createToken();
    return new Ember.RSVP.Promise(function(resolve, reject){
      console.log(authentication);
      Ember.$.ajax({
        url: 'http://localhost/getUserInfoWuthAuthCode.php',
        data: { 'code': authorizationCode,token:token},
        success: Ember.run.bind(null, resolve),
        error: Ember.run.bind(null, reject)
      });
    }).then(function(data){
      let user = data.user[0];
      this.set('storage.token',token); //this is undefined
      return {
        user: user
      };
    });
  }

});

Error i am getting is "TypeError: Cannot read property 'set' of undefined". I am injecting the store service as well. Could you please tell me what exactly is going wrong here?


Solution

  • this is not defined in your current context. Assign it to another varible.

      open: function(authentication){
        let authorizationCode = authentication.authorizationCode;
        let token = createToken();
        let that = this;
        return new Ember.RSVP.Promise(function(resolve, reject){
          console.log(authentication);
          Ember.$.ajax({
            url: 'http://localhost/getUserInfoWuthAuthCode.php',
            data: { 'code': authorizationCode,token:token},
            success: Ember.run.bind(null, resolve),
            error: Ember.run.bind(null, reject)
          });
        }).then(function(data){
          let user = data.user[0];
          that.set('storage.token',token); //this is undefined
          return {
            user: user
          };
        });
      }
    

    To get further understanding and to see different options (such as fat arrow or bind method), have a look at this question.