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;
   }
);

Javascript Namespace

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

order.js
(function(ns){
   ns.Order = function(id, custName){
      this.id = id,
      this.customer = new ns.Customer(custName)
   };
}(window.ProjectNS = window.ProjectNS || {}));

Customer.js
(function(ns){
   ns.Customer = function(name){
      this.name = name
   };
}(window.ProjectNS = window.ProjectNS || {}));