如何在Javascript中监听变量?

时间:2010-09-03 16:38:15

标签: javascript asynchronous couchdb node.js

我一直在使用Node.js和CouchDB。我想要做的是在对象中进行db调用。这是我现在正在看的情景:

var foo = new function(){
   this.bar = null;

   var bar;

   calltoDb( ... , function(){

      // what i want to do: 
      // this.bar = dbResponse.bar;

      bar = dbResponse.bar;      

   });

   this.bar = bar;

}

所有这一切的问题是CouchDB回调是异步的,而“this.bar”现在属于回调函数的范围,而不是类。有没有人有任何想法来完成我想要的东西?我不希望有一个处理程序对象必须对对象进行db调用,但是现在我真的很难理解它是异步的。

2 个答案:

答案 0 :(得分:6)

只需保留对this周围的参考:

function Foo() {
   var that = this; // get a reference to the current 'this'
   this.bar = null;

   calltoDb( ... , function(){
      that.bar = dbResponse.bar;
      // closure ftw, 'that' still points to the old 'this'
      // even though the function gets called in a different context than 'Foo'
      // 'that' is still in the scope and can therefore be used
   });
};

// this is the correct way to use the new keyword
var myFoo = new Foo(); // create a new instance of 'Foo' and bind it to 'myFoo'

答案 1 :(得分:2)

保存对this的引用,如下所示:

var foo = this;
calltoDb( ... , function(){

  // what i want to do: 
  // this.bar = dbResponse.bar;

  foo.bar = dbResponse.bar;      

});