dataService
たとえば と呼ばれる 1 つのモジュールを作成し、その中に変数を入れてから、このモジュールを依存関係として他のモジュールに挿入することで、異なるモジュール間でいくつかのデータを共有したいと考えています。これがコードです(動作しません):
define('dataService', function () {
var quotes = [];
return {
quotesArray: quotes,
};
});
require(['dataService'], function (dataService) {
dataService.quotesArray {1, 2, 3}; // setting the quotes variable
});
define('otherModule', ['dataService'], function (dataService) {
var x = dataService.quotesArray; // x = empty Array, why?
});
回避策は次のとおりです。
define('dataService', function () {
var quotes = [];
var getQuotes = function () {
return quotes;
};
var setQuotes = function (newQuotes) {
quotes = newQuotes;
};
return {
getQuotes: getQuotes,
};
});
require(['dataService'], function (dataService) {
var x = dataService.getQuotes(); // now I can get/set the quotes variable
dataService.setQuotes();
});
一部のデータに異なるモジュールでアクセスできるようにするのが適切な方法であるかどうか疑問に思っていますか?
そして、なぜ最初のオプションが機能しないのですか?