如何将其他参数传递给node.js中的封装回调函数

时间:2013-08-14 12:30:22

标签: javascript node.js asynchronous

多年来一直使用这个网站,但之前从未发过一个问题:-)这里有..

我有一个javascript对象,我想在初始化时根据谷歌API为自己分配一个值。这一切都很好,但谷歌响应不包含对哪个对象称为它的引用,所以我需要找到一种方法将ID传递给链。

我希望下面的例子有意义,基本上我想要的API响应不会包含对启动它的对象的引用 - 所以我需要一种方法将它关联回调用它的对象。

注意:这是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;  :-(

3 个答案:

答案 0 :(得分:2)

在jcubic的回答中,由于distanceFromSomething在完成http.get之前不会设置,因此无法获得所需的结果,因此您需要进行某种回调。

function myClass(param) {
    var self = this;
    this.property = param;
    this.distanceFromSomething = 0;
    this.init = function(cb) {
        // 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;
                self.distanceFromSomething = distance;
                setDistance(ID, distance);
                if(cb) {
                    cb.bind(self)(); // "this" inside the callback will be bound to myClass instance.
                }
            }); 
        };
    };
}

var cls = new myClass({});
cls.init(function() {
    console.log(this.distanceFromSomething); //init is done.
});

答案 1 :(得分:0)

您可以使用apply,call或bind更改函数的范围(this)将返回另一个更改范围的函数。

所以在你的情况下只做

function myClass(param) {
  var self = this;
  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' will be from myClass scope
        // 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?
      }.bind(self)); // <--- HERE bind to self
    };
  };
  this.init();
}

或者你可以在回调中使用self。

编辑在初始化代码中,您需要等到获取值:

var entity = new myClass(foo);
(function delay() {
    if (!entity.distanceFromSomething) {
        return setTimeout(delay, 100);
    }
    alert(entity.distanceFromSomething);
});

答案 2 :(得分:0)

谢谢大家,我使用了一些有效的解决方案组合!

    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';
    var self = this; // 'this' is still defined at this point
    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;
            self.distanceFromSomething = distance;
            setDistance(self.id, distance);  // <-- this function receives self.id :-)
        }); 
    }.bind(self));
};

}