2

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')}
});
c69
  • 19,951
  • 7
  • 52
  • 82
ptmoy2
  • 311
  • 1
  • 4
  • 13

1 Answers1

3

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!

Steve H.
  • 6,912
  • 2
  • 30
  • 49
  • Also, the 2nd console.log will always print the same value as the first. `getJSON()` does not block, it returns immediately and asynchronously calls the `done` function later. – Steve H. Jan 08 '14 at 02:52