繁体   English   中英

如何在Javascript中监听变量?

[英]How to listen for a variable change in Javascript?

我一直在使用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调用,但是现在我真的很难理解它是异步的。

请保持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'

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

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

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

  foo.bar = dbResponse.bar;      

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM