Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a global (on the window) object in Dart lang?

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?

like image 407
corgrath Avatar asked Aug 22 '17 08:08

corgrath


People also ask

How do you make a global variable 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).

Is the window object the global object?

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.

What is global window object?

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.

Is DART pass by reference?

Dart does not support passing by reference. Dart is only passed by value, just like Java. Java also does not support reference passing.


1 Answers

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();
}
like image 139
Jacob Richman Avatar answered Sep 29 '22 05:09

Jacob Richman