How to exchange data between different modules in requirejs, javascript

I want to share some data between different modules by creating one module called for the dataService instance, putting a variable in it, and then insert this module into the other modules as a dependency. Here is the code (which does not 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 a 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 some data can be made available in different modules?

And why does the first option not work?

+6
source share
1 answer

To do this, you need to instantiate both so that 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.net/kmturley/aHgMJ/

+6
source

Source: https://habr.com/ru/post/952524/


All Articles