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

≡放荡痞女 提交于 2019-12-14 01:40:18

问题


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?


回答1:


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();
}



回答2:


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.



来源:https://stackoverflow.com/questions/45812372/how-do-i-create-a-global-on-the-window-object-in-dart-lang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!