How to use extern libraries
There a lot of great JavaScript libraries outside. This page will explain how to use them with haXe together.
Lets say we are having this little quite useless JavaScript, that hides and show an dom element by changing its CSS class:
function DisplayToggle(id) {
this.el = document.getElementById(id);
this.el.className="visible";
this.visible = true;
}
DisplayToggle.prototype.hide() {
this.el.className="hidden";
this.visible = false;
}
DisplayToggle.prototype.show() {
this.el.className="visible";
this.visible = true;
}Save this file as: DisplayToggle.js.
Using: extern class
This is the most elegant way, because it is clean and typesave.
We create a haXe file which defines the functions of our extern JavaScript library. The
extern keywords tells the compiler that this class will be avaible at the runtime.package ; extern class DisplayToogle { public function new(id:String):Void; public function hide():Void; public function show():Void; public var visible(default,null):Bool; }
DisplayToogle.hxNow we can use our external JavaScript directly within haXe. If you use an IDE with autocompletion you will even get autocompletion using this class.
Make sure that the
DisplayToogle.js is embeded in your HTML file before you add you haXe generated JavaScript file.Using: untyped
Warning: This is unsafe. Use it only if you quite sure about what you are doing.
Some where in your haXe code:
class Main { static function main() { var dis:Dynamic = untyped __js__('new DisplayToggle("some_id")'); dis.hide(); } }
The
__js__ command will directly forwards some string to the generated JavaScript. You can read more about this on the haXe magic pageThis way you will get no autocompletion or errors if you try to access a property or function that does not exists.
Also make sure that the
DisplayToggle.js is embeded in you HTML before you haxe generated JavaScript file.Packages
Some notes about the haXe package structure. Lets say we have the following file:
package foo.bar; class FooBar { public function new() { // some code } }
This class will be compiled to a JavaScript object similiar to this:
foo.bar.FooBar = function() {
//some code
}So if you external library stuctured this way you have to recreate the package structure within haXe.
version #6751, modified 2009-08-13 16:19:53 by TheHippo