2
votes

I want to reset a variable in the application controller to a value returned from an AJAX call. The code shown below doesn't work because 'this' doesn't have the correct context. Server returns a value different than 15, but 2nd console.log still outputs 15. I've also tried App.ApplicationController.set ('x', data) and controllers.application.set ('x', data), and a few other possibilities. None worked. What's the correct way of doing this?

App.ApplicationController = Ember.Controller.extend({

x: 15,

init: function() {
console.log(this.get('x'));
$.getJSON ("strats/limits.json")
    .done (function (data){this.set('x', data);});
    console.log(this.get('x')}
});
1

1 Answers

3
votes

Yours is just a JavaScript problem... Try this:

App.ApplicationController = Ember.Controller.extend({

    x: 15,

    init: function() {
        var self= this;
        console.log(self.get('x'));
        $.getJSON ("strats/limits.json")
            .done (function (data){self.set('x', data);});
        console.log(self.get('x');
    }
});

Always be careful using "this" and remember nested functions may have a different value!