Setting an application controller variable for results returned from an AJAX call

I want to reset a variable in the application controller to the value returned from an AJAX call. The code shown below does not work because 'this' does not have the correct context. The server returns a value other than 15, but the second console.log still prints 15. I also tried App.ApplicationController.set ('x', data) and controllers.application.set ('x', data) and several others of opportunities. No one worked. What is the right way to do 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')} }); 
+2
source share
1 answer

You just have a problem with JavaScript ... Try the following:

 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 with "this" and remember that nested functions may have a different meaning!

+2
source share

All Articles