2015-09-07 61 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