2015-09-07 60 views
0

我想以某種方式創建一個全局單例模塊。我使用它作爲上下文模塊,我可以在任何模塊中引用它。在整個Node.js模塊中使用Singleton

,我會用它來獲得我的網關(庫)模塊像我的業務對象模塊等其他模塊使用,因此例如,讓我們說我有:

myBusinessModule.js

module.exports = { 
     find: function(id){ 
     var user = context.userGateway.find(id); 
     } 
}; 

所以,我想能夠使用context單身人士在我的節點應用程序中的其他模塊。

就像這裏一樣的東西,這是Java,但相同的概念我想要做這樣的事情在Node.js的:基於您的評論CleanCodeCaseStudy

+0

什麼是真正的問題在這裏?如何在nodejs中創建單例?模塊在節點中已經是單身。你甚至可以從多個位置從'require()'返回相同的對象。 – rossipedia

+0

是創建一個單身人士,並能夠跨所有節點模塊共享 – PositiveGuy

+0

好,所以它實際上只是創建一個需求也許是一個JSON對象的屬性指向其他要求? – PositiveGuy

回答

0

,對我來說,它看起來像你希望是這樣的。如果我錯誤地理解了你的要求,請糾正我。

與要求()

context.js訪問

var context = {}; 
context.userGateway = require('../path/to/userGateway/module'); 

module.exports.context = context; 
===================================================================================== 

//usage in reference file 
var context = require('/path/to/context/file'); 
module.exports = { 
     find: function(id){ 
     var user = context.userGateway.find(id); 
     } 
}; 

無訪問需要()

var context = {}; 
context.userGateway = require('../path/to/userGateway/module'); 

GLOBAL.context = context; // makes your context object accessible globally, just like, console, require, module etc. 

===================================================================================== 

//usage in reference file 
module.exports = { 
     find: function(id){ 
     var user = context.userGateway.find(id); 
     } 
}; 
+0

非常感謝! – PositiveGuy

+0

@WeDoTDD很高興幫助 – guptakvgaurav