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?
Just create a library file and create fields for globals you need there. Import this library everywhere you need access to these fields. create a singleton in the globals library (see How do you build a Singleton in Dart? for more details).
The global object in JavaScript is an always defined object that provides variables and functions, and is available anywhere. In a web browser, the global object is the window object, while it is named global in Node. js. The global object can be accessed using the this operator in the global scope.
In a web browser, any code which the script doesn't specifically start up as a background task has a Window as its global object.
Dart does not support passing by reference. Dart is only passed by value, just like Java. Java also does not support reference passing.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With