COMMUNITY

How do I create a Haxe class that calls into my own local javascript file?

I want to write a class that my Haxe code can call to execute raw javascript. I read through this guide, but do not understand it enough to make progress.

Here is some pseudo-code to roughly outline what I want to do:

Haxe_translation_class.hx:

#if html5
extern class HaxeGeneralClass {
    @:overload(function(my_javascript_library.init):Void { })
    public static function init():Void;
}
#end

My_javascript_library.js:

static init() {
    console.log("javascript version of library initialized");
}

@:overload metadata is used for when a function can have multiple different sets of arguments.

In your case I think you are looking for the @:native metadata.

For example:

#if html5
@:native("my_javascript_library")
extern class HaxeGeneralClass {
    public static function init():Void;
}
#end

Calling HaxeGeneralClass.init(); will generate the javascript code: my_javascript_library.init();

I just saw this! I didn’t get a notification that someone replied. I think you are right about the native tag, but I have no clue how to get my_javascript_library in scope when the game is actually running. I build my game using lime and it is a haxeflixel game.

What library are you trying to use?
I’m not familiar with haxeflixel or lime but It’s often enough to add <script src="url/to/the/library.js"></script> before your game’s main script tag.

I got it figured out. your solution got me halfway there, so thank you! Haxeflixel seems to have a unique flow. I will outline the steps to my solution here:

  1. In your Project.xml file, add
<dependency path="path/to/file.js" if="html5"/>
  1. Create an extern class in your project that has the same functions and arguments as the javascript class you want to import. The extern class can be named anything, but the @:native native tag must match the javascript class name.
@:native("class_name_to_import")
extern class MyHaxeExternClass {
    public static function function_from_javascript_class():Void;
}

If you want to create a library that calls out to the json class, add the <dependency> tag to an include.xml instead and the contents of that will be appended to the Project.xml of whatever game imports it.