简体   繁体   English

如何在Javascript中监听变量?

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

I've been messing around with using Node.js and CouchDB. 我一直在使用Node.js和CouchDB。 What I want to be able to do is make a db call within an object. 我想要做的是在对象中进行db调用。 Here is the scenario that I am looking at right now: 这是我现在正在看的场景:

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;

}

The issue with all of this is that the CouchDB callback is asynchronous, and "this.bar" is now within the scope of the callback function, not the class. 所有这一切的问题是CouchDB回调是异步的,“this.bar”现在在回调函数的范围内,而不是类。 Does anyone have any ideas for accomplishing what I want to? 有没有人有任何想法来完成我想要的东西? I would prefer not to have a handler object that has to make the db calls for the objects, but right now I am really stumped with the issue of it being asynchronous. 我不希望有一个处理程序对象必须对对象进行db调用,但是现在我真的很难理解它是异步的。

Just keep a reference to the this around: 请保持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'

Save a reference to this , like so: 保存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