Passing Dart objects to js functions in js interop

余生长醉 提交于 2019-12-12 17:38:50

问题


I've been playing around a bit with the new js interop of dart. So far everything was very straight-forward. But one thing I'm not sure about is how to deal with js stuff like this:

MathJax.Hub.Config({
  showProcessingMessages: false,
  showMathMenu: false
  .. many other different options
});

I can translate the MathJax.Hub.Config part:

@JS('MathJax') external MathJaxClass get MathJax;
class MathJaxClass {
  external HubClass get Hub;
}

@JS('MathJax.Hub')
class HubClass {
  external void Config(options);
}

But now I would like to have the options argument of Config function to be a Dart Object. I'm not sure how to do this. The only way, I can get something working is with a Map:

  MathJax.Hub.Config(new JsObject.jsify({
    'showProcessingMessages': false,
    'showMathMenu': false
  }));

But this is surely not ideal. Any ideas?


回答1:


Since a recent update the @anonymous annotation is used to create JS objects from Dart classes instead of a factory constructor.

@JS()
@anonymous
class Config {
  external bool get showProcessingMessages;
  external set showProcessingMessages(bool value);
  external bool get showMathMenu;
  external set showMathMenu(bool value);
}

MathJax.Hub.Config(new Config()
  ..showProcessingMessages= false
  ..showMathMenu = false
}));



回答2:


The syntax is as follows:

@anonymous
@JS()
class Config {
  external bool get showProcessingMessages;
  external bool get showMathMenu;

  external factory Config({bool showProcessingMessages, bool showMathMenu});
}

Here the Config name is not matching any javascript name, so you can name it whatever you want. You can then call it like this:

MathJax.Hub.Config(new Config(
  showProcessingMessages: false,
  showMathMenu: false
));

The object passed to the js function, will be a regular javascript object:



来源:https://stackoverflow.com/questions/33394867/passing-dart-objects-to-js-functions-in-js-interop

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