How to listen for a variable change in Javascript?
I've been messing around with using Node.js and CouchDB. What I want to be able to do is make a db call within an object. Here is the scenario that I am looking at right now:
var foo = new function(){
this.bar = null;
var bar;
开发者_如何学Python
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. 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.
Just keep a reference to the this
around:
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:
var foo = this;
calltoDb( ... , function(){
// what i want to do:
// this.bar = dbResponse.bar;
foo.bar = dbResponse.bar;
});
精彩评论