Backbone.js documentation suggest loading bootstrapped models this way:
<script>
var Accounts = new Backbone.Collection;
Accounts.reset(<%= @accounts.to_json %>);
var Projects = new Backbone.Collection;
Projects.reset(<%= @projects.to_json(:collaborators => true) %>);
</script>
But this is a pattern that can't be used in AMD approach (using require.js)
The only possible solution is to declare global variable storing JSON data and use this variable later in relevant initialize methods.
Is there a better way to do this (without globals)?
Like described above, the 'data module' (or config, or whatever you want to call it) could be included in a file that is already generated anyway (e.g. index.html) but I think this is rather ugly.
Another way would be to declare it in its own module file but this would require an extra roundtrip to the server in production environments. As soon as you want to build and optimize your requirejs dependencies, the data module cannot be included because it is dynamically generated upon page load.
A third option might be to append it to one of the files that you serve (for example, the optimized requirejs file), but I have no idea of how/if that could be done.
In RequireJS this is done with the config option for
requirejs.config()
. Modules can then read that info by asking for the special dependency "module" and callingmodule.config()
. Example:index.html
main.js
app.js
Just note that the name of the configuration-object must match the name of the module. In my example the name of the module was
app
, so the name of the configuration-object needed to be namedapp
as well. In the module, you will need to include['module']
as a dependency and callmodule.config()[property name]
to retrieve the configuration-data.Read the documentation about this: http://requirejs.org/docs/api.html#config-moduleconfig
You could add a loopy function at the end of your AMD module to check for when the init method is defined (so that it can be populated after body, or loaded from an include). that way the module is guaranteed available and initialization can happen when it's ready.