Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred method for passing server data to a RequireJS module?

Tags:

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         }     } }); 
like image 466
brianc Avatar asked May 24 '11 02:05

brianc


People also ask

What is RequireJS used for?

RequireJS is a JavaScript library and file loader which manages the dependencies between JavaScript files and in modular programming. It also helps to improve the speed and quality of the code.

What is require () in JS?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

How do I import a module in HTML?

Here's what they look like. Simply add type="module" to your script tags and the browser will load them as ES Modules. The browser will follow all import paths, downloading and executing each module only once.


1 Answers

I usually do something like this (using PHP on the back-end but anything works):

<script src="scripts/require-jquery.js"></script> <script> require(['scripts/main'], function(App) {   var myApp = new App({     param1: <?=json_encode($param1);?>,     param2: <?=json_encode($param2);?>   }); }); </script> 

And then define my module as something that takes a config:

define(['jquery'], function($) {   var App = function(options) {     this.options = options;     //blabla   }    // add some stuff to App.prototype maybe    // and finally...   return App; }); 
like image 57
ziad-saab Avatar answered Oct 06 '22 01:10

ziad-saab