Search code examples
javascriptember.jspromisersvp-promise

EmberJS "this" changed in promise (find) callback


When I want to fetch an account from the server in an controller action e.g:

account: false,

actions: {

    // When the oAuth popup returns this method will be called
    fetchUser: function(id)
    {           
        // Get the account from the server
        this.store.find('account', id).then(function(account)
        {
            this.set('account', account);
        }, function(error)
        {
            console.log('error', error);
        });

    },
}

It throws an error because "this" on the line this.set('account', account) is no longer the controller. How can I set "account" on the controller now from within this promise callback?


Solution

  • account: false,
    
    actions: {
    
    // When the oAuth popup returns this method will be called
    fetchUser: function(id)
    {           
        // Get the account from the server
        this.store.find('account', id).then(function(account)
        {
            this.set('account', account);
        }.bind(this), function(error)
        {
            console.log('error', error);
        });
    
    },
    

    }

    Fixed it! added .bind(this) :-)