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

I am trying to assign a value to a variable with json (returned from server side). I do not want to use ember-data to manage the models and define the RestAdapter, since 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;
  }
});

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

+4
source share
3 answers

, , hook after after.Model.

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

...

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

, :

var examples;

, ( var) .

0

I agree with kingpin2k, however, if for some reason you still want to follow your path, I would recommend storing data for variables in an ember context, like the controller associated with your example 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
});
0
source

Source: https://habr.com/ru/post/1524940/


All Articles