charleetm
charleetm

Reputation: 906

Emberjs a good way to handle async ajax calls

I am quite new to emberjs and would like to know what is the best way to deal with something like the following:

View:

{{#if model}}
  <p>I exist</p>
{{else}}
  <p>Login first</p>
{{#if}}

In my JS:

App = Em.Application.create({});

App.MyRoute = Em.Route.extend({
  setupController: function(){
    $.get("some/ajax/call",function(data){
        controller.set('model', data)});
    }
  }
}};

In the above example setupController will complete and flashes the <p>Login First</p> and when the data arrive form the ajax call it changes to <p>I exist</p> I try to do this in a model the result is the same.

Currently I use some jquery to hide and unhide stuff to get around this but I don't think is the best way? seems abit brittle to me. any advice will be really helpful

Thanks

Upvotes: 1

Views: 186

Answers (1)

Darshan Sawardekar
Darshan Sawardekar

Reputation: 5075

You can use the afterModel hook to perform any checks. This hook fires with the model that was returned by jQuery, but before setupController.

model: function() {
  return $.get("some/ajax/call",function(data){
      return data;
  }
},

afterModel: function(model) {
  // if model is not valid 
  // transitionTo another route etc
}

Note that you just return the data from the jQuery promise. Ember understands that when a promise is resolved with a value it is the model.

Upvotes: 1

Related Questions