[go: up one dir, main page]

Writing Libraries

Writing your own libraries is a great way to make your code more modular and let other people reuse your work. Give your app a name starting with lib-, and put any code you want to expose as a library in an /* appjet:library */ section.

Here's a simple "hello, world!" library.

/* appjet:library */

function hi() {
    print("Hello, World!");
}

Then just import your library as you would any other library.

import("lib-hi");

hi();

Any top-level function or variable is included. You can hide anything you don't want exposed, like a helper function or variable, by prefixing its name with an underscore (_) character.

Here's another "hello, world!" library, one that has some hidden items and then uses itself in an /* appjet:server */ section.

/* appjet:library */

var _theString = "Hello, again!";
var anotherString = "Hello, thrice!";

function _hiHelper() {
    printp(_theString);
}

function hi() {
    _hiHelper();
}

/* appjet:server */

import("lib-hi2");

hi();
printp(anotherString);

try {
    print(_theString);
} catch (err) {
    print(err)
}

Tou can use the /* appjet:server */ section of a library in a variety of ways. In the example above, the /* appjet:server */ section is a sanity check for the library itself, but you can also use this space to describe your library, provide example uses, or write some unit tests.

Further Notes:

  • The functions and variables defined by a library can be imported into a specific "scope" by passing an object as the first argument to import(). For example, to import lib-hi into an object "hi": var hi = {} ; import(hi, "lib-hi").

  • Libraries can import other libraries -- but in order to prevent functions and items defined in those libraries to leak back to the original importing code, we recomment that any libraries your library imports are imported into a "hidden" object, that is, one whose name starts with an underscore(_) character.

© Copyright 2007-2008 AppJet Inc.