Monday, December 24th, 2007

Organise Your Code With base2.Packages

Category: JavaScript, Library

<>p>Since Dean Edwards announced base2 beta he has been taking some time to describe it for us.

His latest installment is on base2 packages:

A base2.Package provides a mechanism for bundling classes, constants and functions within a closure. You can define what symbols you want to export from the Package and you can define the symbols you want to import into the closure.

The package concept is used throughout base2 itself to manage components and namespaces.

The template for creating a package is:

javascript
< view plain text >
  1. new function(_) { // create the closure
  2.   // create the package object
  3.   var MyPackage = new base2.Package(this, {
  4.     name:    "MyPackage",
  5.     version: "1.0",
  6.     imports: "SomeOtherPackage",
  7.     exports: "MY_CONSTANT,MyClass,myFunction"
  8.   });
  9.  
  10.   // evaluate the imported namespace
  11.   eval(this.imports);
  12.  
  13.   // define package contents
  14.  
  15.   var MY_CONSTANT = 42;
  16.  
  17.   var MyClass = SomeOtherClass.extend({
  18.     // class definition
  19.   });
  20.  
  21.   function myFunction() {
  22.     return "Hello!";
  23.   };
  24.  
  25.   // evaluate the exported namespace (this initialises the Package)
  26.   eval(this.exports);
  27. };

and here is an example that uses one:

javascript
< view plain text >
  1. new function(_) { // create the closure
  2.   // create the package object
  3.   var graphics = new base2.Package(this, {
  4.     name:    "graphics",
  5.     version: "1.0",
  6.     imports: "shapes",
  7.     exports: "Layout"
  8.   });
  9.  
  10.   // evaluate the imported namespace
  11.   eval(this.imports);
  12.  
  13.   // we can refer to the Rectangle class directly because we have imported the
  14.   // shapes Package.
  15.   var Layout = Rectangle.extend({
  16.     // I don't know anything about graphics  
  17.   });
  18.  
  19.   // evaluate the exported namespace (this initialises the Package)
  20.   eval(this.exports);
  21. };

Related Content:

Posted by Dion Almaer at 7:37 am
1 Comment

+++--
3.3 rating from 25 votes

1 Comment »

Comments feed TrackBack URI

As for me – it’s uncomfortable thing…

Comment by Snowcore — December 24, 2007

Leave a comment

You must be logged in to post a comment.