2010-09-03 19 views
11

Node.js ve CouchDB'yi kullanarak uğraştım. Yapabileceğim şey, bir nesne içinde bir db çağrısı yapmak. İşte şu anda bakıyorum senaryodur:Javascript'te değişken bir değişiklik nasıl dinlenir?

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; 

} 

tüm bunlarla sorunu CouchDB geri arama "this.bar", geri arama işlevi kapsamına şimdi değil asenkron ve olmasıdır sınıf. İstediğim şeyi başarmak için herhangi bir fikri var mı? Nesneler için db çağrıları yapmak zorunda olan bir işleyici nesnesine sahip olmamayı tercih ederim, ancak şu anda gerçekten asenkronize olma sorunuyla karşılaştım.

+2

Welcome yığın taşması, + 1'e iyi bir soru için. –

cevap

6

Öylesine this bir başvuru tutmak:

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

OP'nin 'yeni fonksiyon ...' için bir tekton yaratma tekniğine gittiğine inanıyorum, bu yüzden kodu olduğu gibi iyiydi. – James

+0

Bu bir singleton değil, sadece tek bir yalnız nesne yaratıyor. Tek kişilik anlayışım, kurucuyu başka bir kez çağırırsanız, aynı nesneye sahip olmanızdır. –

+0

Evet, 'yeni işlev() {}' bir nesneye neden olur, ancak '' fonksiyonu() {} 'kendi başına anonim bir tekildir. – James

2

Kaydet referans this için, şöyle:

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

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

    foo.bar = dbResponse.bar;  

}); 
+0

node.js v2 (aslında yeni V8'tir) işlev bağlamasını destekler, bu nedenle 'bu' etrafında dolaşmak için ek değişkenlere gerek yoktur: 'calltoDB (..., işlev() {this.bar = dbResponse.bar} .bind (Bu)); ' – Andris

İlgili konular