2015-08-30 120 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,你認爲有更好的方法來做到這一點嗎? –