I've encountered some unexpected behavior while trying to set an Ember property inside a custom AJAX function callback.
The AJAX function is triggered in the route, as seen in the code snippet below. The success callback updates the 'session.ajaxStatus' property from 'checking' to 'success' when a successful response is received. It consistently logs 'route: success' in the console from the callback function.
The issue arises when I attempt to observe and react to that property in a component. Occasionally, the observer recognizes the update from 'checking' to 'success', but other times it does not.
My assumption is that this discrepancy could be due to the varying response times. To address this, I wrapped the AJAX function in Ember.run to ensure it operates within the Ember run loop.
How can I guarantee that the observer binding always functions correctly? Should I consider revising the entire approach?
Route:
session: Ember.inject.service(),
...
actions: {
ajaxRequest: function() {
Ember.run(this, function() {
var self = this;
var url = self.get('session.url');
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'),