¶ Edit

X Delete

2270 views

8 years ago

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

You 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.

When you are ready to share your library with other people, AppJet can automatically generate documentation by parsing special comments. Read more about this in Documenting Code.

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.

Powered by AppJet on JGate
source
rendered in 0.140s