2015-08-30 123 views
0

我有节点模块,我需要解析数据,我想在不同的模块中共享这个解析的属性。第一个调用这个模块负责传递数据和其他模块不需要发送数据,因为我已经存储了parsedData(在cacheObj中)并且可以使用刚刚获得的任何属性,问题是当我从1个模块访问并提供数据然后尝试访问diff模块时,缓存对象不包含我“存储”的数据,任何想法如何做到这一点对吗?从diff模块访问模块数据

"use strict"; 
var Parser = require('myParser'), 
    _ = require('lodash'); 

function myParser(data) { 
    if (!(this instanceof myParser)) return new myParser(data); 
    if (!_.isEmpty(this.cacheObj)) { 
     this.parsedData = this.cacheObj; 
    } else { 
     this.parsedData = Parser.parse(data); 
     this.cacheObj = this.parsedData; 
    } 
} 

myParser.prototype = { 
    cacheObj: {}, 
    getPropOne: function() { 
     return this.parsedData.propOne; 
    }, 

    getPropTwo: function() { 
     return this.parsedData.propTwo; 
    } 
}; 

module.exports = myParser; 

的数据应该是我的节点应用程序,所以我不需要每次都传同...只是为了“初始化” ......

回答

1

使用单一对象,下面

基本样本
var Singleton = (function() { 
    var instance; 

    function createInstance() { 
     var object = new Object("I am the instance"); 
     return object; 
    } 

    return { 
     getInstance: function() { 
      if (!instance) { 
       instance = createInstance(); 
      } 
      return instance; 
     } 
    }; 
})(); 

在你的情况下,使用同样的方法

"use strict"; 
var Parser = require('myParser'), 
    _ = require('lodash'); 

var cacheObj; // <-- singleton, will hold value and will not be reinitialized on myParser function call 

function myParser(data) { 
    if (!(this instanceof myParser)) return new myParser(data); 
    if (!_.isEmpty(cacheObj)) { //remove `this` 
     this.parsedData = cacheObj; //remove `this` 
    } else { 
     this.parsedData = Parser.parse(data); 
     cacheObj = this.parsedData; //remove `this` 
    } 
} 

myParser.prototype = { 
    //remove `this.cacheObj` 
    getPropOne: function() { 
     return this.parsedData.propOne; 
    }, 

    getPropTwo: function() { 
     return this.parsedData.propTwo; 
    } 
}; 

module.exports = myParser; 

使用memory-cache,不要忘记安装

"use strict"; 
var Parser = require('myParser'), 
    _ = require('lodash'); 
var cache = require('memory-cache'); 

function myParser(data) { 
    if (!(this instanceof myParser)) return new myParser(data); 
    var cache_data = cache.get('foo'); 
    if (!_.isEmpty(cache_data)) { 
     this.parsedData = JSON.parse(cache_data); 
    } else { 
     this.parsedData = Parser.parse(data); 
     cache.put('foo', JSON.stringify(this.parsedData)); 
    } 
} 

myParser.prototype = { 
    getPropOne: function() { 
     return this.parsedData.propOne; 
    }, 

    getPropTwo: function() { 
     return this.parsedData.propTwo; 
    } 
}; 

module.exports = myParser; 
+0

正确的,但我想避免使用全局varible(你的第二个EG),还有一个办法做到这一点?这是不好的设计中使用它.. –

+0

这不是全局变量,它只存在于该文件中 –

+0

是的,但这是全局AFAIK,你认为有更好的方法来做到这一点吗? –