2010-09-03 8 views
11

Ich habe mit Node.js und CouchDB herumgemacht. Was ich tun möchte, ist einen DB-Aufruf innerhalb eines Objekts zu machen. Hier ist das Szenario, das ich jetzt stehe auf:Wie auf eine variable Änderung in Javascript zu hören?

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; 

} 

Das Problem mit all dies ist, dass der CouchDB Rückruf asynchron ist, und „this.bar“ ist jetzt im Rahmen der Callback-Funktion, nicht die Klasse. Hat jemand irgendwelche Ideen, um das zu erreichen, was ich will? Ich würde es vorziehen, kein Handler-Objekt zu haben, das die db-Aufrufe für die Objekte machen muss, aber im Moment bin ich wirklich mit dem Problem konfrontiert, dass es asynchron ist.

+2

Willkommen bei Stack-Überlauf, +1 für eine gute Frage. –

Antwort

6

Halten Sie einfach einen Verweis auf die this um:

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

Ich glaube, dass das OP für die 'neue Funktion ...' Technik für die Schaffung eines Singleton ging, also war sein Code in Ordnung, wie es war. – James

+0

Das ist kein Singleton, er schafft nur ein einziges einsames Objekt. Mein Verständnis eines Singleton ist, dass, wenn Sie den Konstruktor ein anderes Mal aufrufen, Sie das exakt gleiche Objekt erhalten. –

+0

Ja, die 'neue Funktion() {}' führt zu einem Objekt, aber die 'function() {}' selbst ist im Wesentlichen ein anonymer Singleton. – James

2

Speicher einen Verweis auf this, etwa so:

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

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

    foo.bar = dbResponse.bar;  

}); 
+0

node.js v2 (eigentlich ist es der neue V8) unterstützt die Funktion binding, so dass zusätzliche Variablen nicht benötigt werden, um 'this' zu übergeben:' calltoDB (..., function() {this.bar = dbResponse.bar} .bind (this)); ' – Andris

Verwandte Themen