Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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/

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top