I want to share some data between different modules by creating one module, called for instance dataService
, put a variable into it, and then insert this module in other modules as a dependency. Here is the code (that doesn't work):
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?
});
Here is the workaround:
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();
});
I'm just wondering if it is a proper way to make some data be accessible in different modules?
And why first option doesn't work?
I want to share some data between different modules by creating one module, called for instance dataService
, put a variable into it, and then insert this module in other modules as a dependency. Here is the code (that doesn't work):
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?
});
Here is the workaround:
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();
});
I'm just wondering if it is a proper way to make some data be accessible in different modules?
And why first option doesn't work?
undefined
, there is a circular reference between the modules. So does the first module requires also the second module in your real code.
– Andreas Köberle
Commented
Aug 26, 2013 at 18:49
To make this work you need to create an instance of both, so one overwrites the properties of the other:
define('Quotes', function (Module) {
return {
quotesArray: ['a', 'b', 'c']
};
});
define('Service', ['Quotes'], function (quotes) {
console.log(1, quotes.quotesArray); // ["a", "b", "c"]
quotes.quotesArray = [1, 2, 3];
});
require(['Service', 'Quotes'], function(service, quotes) {
console.log(2, quotes.quotesArray); // [1, 2, 3]
});
Here's a working fiddle: http://jsfiddle/kmturley/aHgMJ/