Jacob Phillips
Jacob Phillips

Reputation: 9264

How does Dart2JS convert a Dart function to a JS function?

When passing Dart functions to Javascript code, the current convention is to use allowInterop() from package:js (presumably). This works pretty well but it creates a closure, which is not allowed by Javascript code that expects a constructor function.

I've done some digging, but arrive at a dead end here:

external DART_CLOSURE_TO_JS(Function function);

Where does this go? Is it open source?

Would it be possible for a Dart function to be converted to a non-closure JS function in either package:js or dart:js? If not, why?

Upvotes: 2

Views: 522

Answers (1)

Jenny Messerly
Jenny Messerly

Reputation: 466

A Dart function wouldn't work as a JS constructor, because it wouldn't have the proper prototype set up. Also with custom elements there's another difficulty: it has to delegate correctly to the DOM element constructor.

The normal way to do that is with an ES6 class. I made an example of using JS to define the custom element class. I think you may have seen, but linking it here just in case: Dart custom element interop demo. The file web/interop.js defines the custom element class.

I think an ES5 constructor would work too, if it used Reflect.construct(). I spent some time last week seeing if that would help retrofit dart:html to work with custom elements, but I don't think it's enough. Dart will need some better JS interop capabilities.

In the meantime, my suggestion is to define custom element classes in JS and use interop to talk to Dart (and vice versa).

Upvotes: 4

Related Questions