Skip to content

Runtime ~ Calling Jangaroo from JavaScript

Frank Wienberg edited this page Mar 14, 2014 · 1 revision

Calling Jangaroo from JavaScript

When including Jangaroo code into a web site, you will typically make the first invocation of Jangaroo code in JavaScript and then do most of the work in Jangaroo. Jangaroo classes can be accessed from JavaScript in the same way as they would be accessed from Jangaroo code, with only two minor limitations.

In JavaScript there is no import directive. At runtime, Jangaroo packages are just nested JavaScript objects, where top-level packages are defined in the global object (window) which is always in scope. Therefore, you must usually reference classes by their fully qualified name. That is, to access the constructor of the class UsedClass in the package com.acme, you must write new com.acme.UsedClass() and not new UsedClass().

When calling Jangaroo from JavaScript, you have to be careful when accessing a static field (variable or constant) of a Jangaroo class. You must check whether the class is guaranteed to be initialized. If it may not be, call

joo.classLoader.init(com.acme.UsedClass);

from JavaScript to initialize the class com.acme.UsedClass. The situation in which it is most likely to forget initialization is when constants of another class are used in a constructor invocation or static method call. Because the constants are evaluated first, the class must be initialized explicitly.

Starting with version 0.3, Jangaroo provides an alternative for explicit class initialization. The missing import directive is simulated by the method import_ of joo.classLoader. (We had to postfix with an underscore, because import is a reserved keyword in JavaScript.) Importing a class for use in JavaScript has three effects:

  1. If the class is not yet prepared, it is loaded.
  2. On complete(), the class is initialized.
  3. The callback function given to complete() receives an argument that has to be used in a with-statement in order to put the imported classes in scope.

Sounds more complicated than it is. Just have a look at this simple example:

with (joo.classLoader) {
  import_("com.acme.UsedClass");
  complete(function(imports){with(imports){
    window.alert(UsedClass.CONSTANT);
  }});
}

Because com.acme.UsedClass is imported, the main code can use the class without the fully qualified name and access a static field without explicitly initializing the class.

While Jangaroo does not support with and we usually discourage its use even in JavaScript code, we consider the JavaScript bootstrap code an exception. The with (joo.classLoader) statement allows to write multiple imports and the complete invocation without repeating joo.classLoader over and over, and the import_ function call more closely resembles the corresponding ActionScript syntax.

Clone this wiki locally