dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.24k stars 1.57k forks source link

Add methods to JS classes via Dart #30554

Open nex3 opened 7 years ago

nex3 commented 7 years ago

There's currently no way for (non-SDK) Dart code to modify a class's prototype, which makes it difficult to expose Dart-like APIs for JS classes without resorting to inefficient wrapper objects. For example, we might want to expose Node.js's net.Server.close([callback]) method so it exposes a more Dart-y future API:

@JS()
class Server {
  Future close();
}

dart:html does this frequently, but the inability to do it outside the SDK means that user-defined JS wrappers can't provide APIs that are as usable as those in the SDK.

I propose we add an @OnPrototype([String jsName]) annotation to the js package that explicitly indicates that a method should be added to the class's prototype. For example:

@JS()
class Server {
  @JS("close")
  void _close([void callback([error])]);

  @OnPrototype("dart_close")
  Future close() {
    // ...
  }
}
a14n commented 7 years ago

Similar to #24779 ?

aemino commented 6 years ago

This feature would be extremely useful. I'm not even sure if it's possible to create a workaround until this feature is implemented. Are there any plans for this?

Also, to achieve the requested functionality, it might not be necessary to modify the prototype of a class at all. Perhaps all methods not marked as external could be interpreted as non-JS methods?