簡體   English   中英

如何將其他參數傳遞給node.js中的封裝回調函數

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

多年來一直使用這個網站,但之前從未發過一個問題:-)

我有一個javascript對象,我想在初始化時根據谷歌API為自己分配一個值。 這一切都很好,但谷歌響應不包含對哪個對象稱為它的引用,所以我需要找到一種方法將ID傳遞給鏈。

我希望下面的例子有意義,基本上我想要的API響應不會包含對啟動它的對象的引用 - 所以我需要一種方法將它關聯回調用它的對象。

注意:這是PSUDO代碼

    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;  :-(

在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.
});

您可以使用apply,call或bind更改函數的范圍(this)(bind將返回另一個更改范圍的函數)。

所以在你的情況下就這樣做

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);
});

謝謝大家,我使用了你的解決方案的組合工作!

    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));
};

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM