jeudi 2 mars 2017

Ember - ensure that bindings work when setting properties in callback of a custom AJAX function

I am getting some unpredictable behaviour when setting an Ember property in the callback of a custom AJAX function.

The AJAX function is fired in the route as shown below. The success callback updates the property 'session.ajaxStatus' from 'checking' to 'success'. This happens correctly every time a success response is received, and the console logs 'route: success' from the callback function.

The problem is that I am trying to observe and react to that property in a component. Sometimes this observer recognises that 'session.ajaxStatus' has updated from 'checking' to 'success' but sometimes it doesn't.

My guess is that this has to do with how long it takes for the response to be returned. I have wrapped by AJAX function in Ember.run as recommended, to try and ensure that it happens in the Ember run loop.

Is there something I can do to ensure that the observer binding always works, or should I revise the entire pattern?

Route:

session: Ember.inject.service(),

...

actions: {
  ajaxRequest: function() {
    Ember.run(this, function() {
      var self = this;
      self.set('session.ajaxStatus', 'checking');
      console.log('route: ' + self.get('session.ajaxStatus'));
      Ember.$.ajax({
        url: url,
        type: "GET",
        success: function(response) {
          console.log('success response');
          callBack(response);
        },
        error: function(response) {
          self.set('session.ajaxStatus', 'error');
        }
      });
      callBack = function(jobsInLicense) {
        self.set('session.ajaxStatus', 'success');
        console.log('route: ' + self.get('session.ajaxStatus'));
        //Always logs 'route: success'.
      };
    });
  },
}

Component:

session: Ember.inject.service(),

checkAjaxStatus: function() {
  console.log('component: ' + this.get('session.ajaxStatus'));
  //Sometimes nothing is logged.
}.observes('session.ajaxStatus'),



Aucun commentaire:

Enregistrer un commentaire