1

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?

Matthijn
  • 3,126
  • 9
  • 46
  • 69

3 Answers3

6
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) :-)

Matthijn
  • 3,126
  • 9
  • 46
  • 69
1

That is not EmberJS doing that, that's just the way Javascript scopes work.

The this keyword's scope is the function in which it is used.

Here's a link that will help you understand this..

http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/

I also suggest watching Crockford's videos on Javascript, he explains this and the workaround for what you're trying to do.

Here's a link to his videos..

http://yuiblog.com/crockford/

martskins
  • 2,920
  • 4
  • 26
  • 52
0

One solution is to use the typical

var self = this; 

Before entering the function that changes the scope of this and using self instead of this from within the function.

self.set('account', account);
html_programmer
  • 18,126
  • 18
  • 85
  • 158
  • This approach doesn't work for ember object. `var self = this;` will throw an error. You would need to set it like this `self:this.` as an object property assignment. But that wouldn't get you anywhere because you would need to used "this" to reference it anyway `this.self` – Caranicas Sep 15 '14 at 21:12