Wednesday, 14 August 2013

How to pass additional parameters to an encapsulated callback function in node.js

How to pass additional parameters to an encapsulated callback function in
node.js

Have used this site for years but never posted a question before :-) Here
goes..
I have a javascript object, which I would like to assign itself a value
based on a google API when it's initialised. That's all fine, but the
google response doesn't contain the reference to which object called it,
so I need to find a way to pass the ID down the chain.
I hope the below example makes sense, basically the API response I want
will not contain a reference to the object that started it - so I need a
way of associating it back to the object that called it.
NOTE : THIS IS PSUDO CODE
function myClass(param) {
this.property = param;
this.distanceFromSomething = 0;
this.init = function() {
// this will set this.distanceFromSomething
var url = 'http:// GOOGLE MAPS API URL BUILT HERE';
http.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {body += chunk;});
res.on('end', function() {
var response = JSON.parse(body)
var distance = response.distance;
this.distanceFromSomething = distance;
// 'this' is no longer defined since it's asynchronous... :-(
// alternative...
setDistance(ID, distance);
// and I cannot get the ID of the current object from here
either, since it's encapsulated :-(
// How can this callback function understand which object it
relates to?
});
};
};
this.init();
}
var entity = new myClass(foo);
var undefined = entity.distanceFromSomething; :-(

No comments:

Post a Comment