2010-09-03 33 views
11

我一直在使用Node.js和CouchDB。我想要做的是在一個對象內進行數據庫調用。下面是我在看現在的情形:如何聆聽Javascript中的變量更改?

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; 

} 

與所有這一切的問題是,CouchDB的回調是異步的,「this.bar」現在是回調函數的範圍之內,不班上。有沒有人有任何想法來完成我想要的?我不希望有一個處理程序對象必須使數據庫調用對象,但現在我真的難以解決它是異步的問題。

+2

歡迎堆棧溢出,一爲一個很好的問題。 – 2010-09-03 16:59:41

回答

6

參考只要保持在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' 
+1

我相信OP是爲了創建一個singleton而使用'new function ...'技術,所以他的代碼很好。 – James 2010-09-03 16:52:40

+0

這不是一個單身人士,他只是創造一個孤獨的對象。我對單身人士的理解是,如果你再次調用構造函數,就會得到完全相同的對象。 – 2010-09-03 16:57:30

+0

是的,'new function(){}'產生一個對象,但'function(){}'本身就是一個匿名單例。 – James 2010-09-03 17:00:44

2

保存一個參考this,像這樣:

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

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

    foo.bar = dbResponse.bar;  

}); 
+0

node.js v2(實際上它是新的V8)支持函數綁定,因此不需要額外的變量來傳遞'this':'calltoDB(...,function(){this.bar = dbResponse.bar} .bind (本));' – Andris 2010-09-07 20:28:09