views:

136

answers:

2

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;

   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.

+2  A: 

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'
Ivo Wetzel
I believe the OP was going for the `new function...` technique for creating a singleton, so his code was fine as it was.
J-P
That's not a singleton, he's just creating a single lonely object. My understanding of a singleton is that if you call the constructor another time, you get the exact same object.
Ivo Wetzel
Yes, the `new function(){}` results in an object, but the `function(){}` by itself is essentially an anonymous singleton.
J-P
this is what i was looking for. thanks. I wasn trying to make a function, btw, not a singleton, I have just been staring at code for too long today and got a little mixed up.
dave
+1  A: 

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;      

});
J-P
node.js v2 (actually it's the new V8) supports function binding, so additional variables are not needed to pass `this` around: `calltoDB( ... ,function(){this.bar=dbResponse.bar}.bind(this));`
Andris