Saturday, October 20, 2012

Javascript Namespace with Require.js

index.html
<script src="scripts/require.js" data-main="scripts/lib/main.js"></script>

main.js
require(["Order"], function(Order){
   var o = new Order(1, "A Customer");
   alert(o.id);
   alert(o.customer.name);
});

Order.js
define('"Customer"],         // Required scripts (Customer)
   function(Customer){          // Get Required objects
      function Order(id, custName){
         this.id = id;
         this.customer = new Customer(custName);
      }
      return Order;
   }
);

Customer.js
define([],
   function(){
      function Customer(name){
         this.name = name;
      }
      return Customer;
   }
);

No comments: