Assigning value to a variable from ajax call in ember.js

I am trying to assign value to a variable with json(returned from server side). I don't want to use ember-data for managing models and defining a RestAdapter as it is still in beta.

App.ExamplesRoute = Ember.Route.extend({
  beforeModel: function() {
    var request = $.post("/Example/GetExamples");
      request.then(this.success.bind(this), this.failure.bind(this));
  },
  success: function(data) {
    var examples=data;
    alert(example);
    if(examples==null){
      alert('examples are null');
    }
  },

  failure: function() {
    alert('failed');
  },

  model: function() {
    return examples;
  }
});

Basically I am trying to assign a value to examples variable from a json object. The problem is that I get a javascript error saying examples is not defined in model: function() { return examples; } }); So what would be the correct way to do this?

Answers


The proper way to set up a route is like this, if you want to check out the value you would do this in the afterModel hook.

App.ExamplesRoute = Ember.Route.extend({
  model: function() {
    return $.post("/Example/GetExamples");
  }
  afterModel: function(model) {
    console.log(model);
  }
});

I would think...

success: function(data) {
  var examples=data;
  alert(examples);
  if(typeof(examples)==='undefined'){
    alert('examples are null');
  }
},

If you want to access it outside of the success functions scope, add:

var examples;

above your function, then set it (without using var) in the success.


I agree with kingpin2k, however if for some reason you still want to follow your path i would recommend storing data to variables within the ember context as would be the controller associated to your examples route.

http://emberjs.jsbin.com/OViyEpOd/1/edit

App.ExamplesRoute = Ember.Route.extend({
  beforeModel: function() {
    var request = $.post("/");/*should use your own url here*/
      request.then(this.success.bind(this), this.failure.bind(this));
  },
  success: function(data) {
    //var examples=data;

    this.controller.set("examples",data.length);/*or something else useful*/
    if(Em.isEmpty(this.controller.get("examples"))){//===null){
      alert('examples are null');
    }
  },
  failure: function() {
    alert('failed');
  }
});

App.ExamplesController = Ember.Controller.extend({
  examples:null
});

Need Your Help

Bootstrap Modal - make background clickable without closing out modal

html css twitter-bootstrap

I would like to have a pop up dialog appear next to a form with guidance on how to fill out the form.

Hosting WCF service created in VS2010 on IIS

c# visual-studio-2010 wcf iis

I have been through tons of threads and am unable to find the correct answer for my question. I have created a very simple WCF service on my development machine using visual studio 2010. The serv...