Let's say I want to create a global object called Hello
and add the function world
on that object, so that any other JavaScript library in the browser can simply call it with window.Hello.world();
How do I create such an object in Dart lang and how do I expose it / place it globally / on the window
object?
In plain JavaScript, I would be able to write:
window.Hello = {
world: function() {
console.log("Hello World!");
}
}
window.Hello.world();
But how do you do this in Dart?
I work on Dart-JS interop. Here is the cleanest way to do it using the new package:js/js.dart interop.
@JS()
library your_library;
import 'package:js/js.dart';
@anonymous
@JS()
class HelloObject {
external factory HelloObject({Function world});
external world();
}
@JS()
external set Hello(HelloObject v);
@JS()
external HelloObject get Hello;
main() {
Hello = new HelloObject(world: allowInterop(() { print("Hello from dart"); }));
// You can also call this object from Dart as an added bonus.
// For example you could call this from Dart or Js.
/// Hello.world();
}
I am not sure how it will work with objects, but if you want to do that for methods, it's quite simple:
import 'dart:js' as js;
main() {
js.context['methodFromDart'] = doMyStuff;
}
void doMyStuff(String text) => print(text);
And then in you Javascript you are free to do:
methodFromDart("Hello world to Dart!");
You can try to find a way how to do similar things to objects.