Right now I have a Knockout computed function that takes certain variables and make an ajax call to google directionsService to get distance between two locations. And I have some calculations done on the callback function of the ajax request. What I would like to do is to make the ajax call only when location variables change so that it does not make api calls every time a ko observable change.
This was my initial code:
ko.computed(function () {
if (checkStatus() !== "invalid-data") {
// Encode address for google API
var start = self.start().split(' ').join('+');
var end = self.end().split(' ').join('+');
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsServices.route(request, function (response, status) {
if (status === "OK") {
// calculations
} else {
console.error("Error: " + status);
}
});
}
}
}, self);
And this was my attempt to refactor the API call:
function getTripData() {
var request = {
origin: start,
destination: start,
waypoints: [{
location: end
}],
travelMode: google.maps.TravelMode.DRIVING
};
return $.Deferred(function(dfd) {
directionsServices.route(request, dfd.resolve());
}).promise();
}
if (locationsChanged) {
trip = getTripData();
trip.done (function() {
console.log(trip.status);
console.log(trip.response);
});
}
I know this isn't right and the code doesnt work either. I could not really understand the JQuery docs on deferred and promise objects. If anybody can help me figure this out that would be great.
Aucun commentaire:
Enregistrer un commentaire