Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple example for using require.js

Tags:

I am trying to learn how to use require.js. So I made an HTML page with the following tags in the body.

<script type="text/javascript" data-main="../js/shirt" src="../js/require.js"></script> <script type="text/javascript">     alert("Shirt color is " + shirt.color); </script> 

The ../js/shirt.js has the following code

define({     color: "black",     size : "large" }); 

How can I use this simple value pairs in my html?

like image 226
Ibrahim Avatar asked May 07 '12 15:05

Ibrahim


2 Answers

In addition to Domenic's answer maybe you prefer this way of using the define function without using require functions inside the modules.

// shirt.js define({     color: "black",     size : "large" });  // logger.js define(["shirt"], function (shirt) {     return {         logTheShirt: function () {             console.log("color: " + shirt.color + ", size: " + shirt.size);         }     }; });  // main.js define(["shirt", "logger"],function (shirt, logger) {         alert("Shirt color is: " + shirt.color);     logger.logTheShirt(); }); 

I prefer this way, but it's only a matter of taste I guess. (I'm assuming that all the scripts are on the same folder.)

like image 171
Gabriel Jürgens Avatar answered Sep 16 '22 19:09

Gabriel Jürgens


In addition to Joseph's answer, you can also write other modules that depend on shirt (which is where the real power of RequireJS comes in).

// shirt.js define({     color: "black",     size : "large" });  // logger.js define(function (require) {     var shirt = require("./shirt");      return {         logTheShirt: function () {             console.log("color: " + shirt.color + ", size: " + shirt.size);         }     }; });  // main.js define(function (require) {     var shirt = require("./shirt");     var logger = require("./logger");      alert("Shirt color is: " + shirt.color);     logger.logTheShirt(); }); 

Then your HTML can just be

<script data-main="../js/main" src="../js/require.js"></script> 
like image 40
Domenic Avatar answered Sep 18 '22 19:09

Domenic