Is there a preferred way to pass server data in a RequireJS module? Our current implementation looks like the following code snippets; using a ‘page’ object to hold any server/dynamic data and passing that to the main bootstrap. (We don’t want to use ajax to populate any dependencies at this time)
From a server page :
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<script type="text/javascript">
define("page", function () {
return { guid: "<%=Guid.NewGuid() %>" };
});
</script>
main.js
require(["jquery", "jquery.alpha", "page"], function ($, alpha, page) {
alpha.initialize(page);
});
jquery.apha.js
define(["jquery", "page"], function ($, page) {
return {
initialize: function () {
console.log(page.guid);
//logs guid as expected
}
}
});
RequireJS says nothing about how to deal with server data, as it is a means to modularize your javascript. So in that regard there is no defacto standard and you can combine RequireJS with json, ajax, php, embedded xml etc however you want.
Two Approaches
There generally are two ways to go about this.
makes it accessible to its users (similar to your current approach, see code sample below)
The first approach adds parameters to your functions.
The second provides global access. This also requires your own initialization code to start fetching data.
It comes down to personal preference and how many of these ‘dao’s’ you have. If you have more than one it might become poluting as you need a new parameter for each dao module. In that case making them global seems cleaner.
A problem with your approach
There is a problem with your current approach though, where you have the Page module as a definition (using
define()instead ofrequire()), because a define module is created for each object that depends on it. This potentially means multiple calls within the same page. Instead use:This way RequireJS recognizes page as a module because it is a seperate file and it will go to your server only once per page.