Edit: 这是一个说明我的问题的最小项目。 https://github.com/ahirschberg/dart-js-interop-toy您可以通过将其提供给浏览器来查看所描述的错误:pub get
然后要么pub serve
(飞镖)或pub build --mode=debug
(其它浏览器)。
如何通过 JsObjectImpl 从 Dart 访问任意 JavaScript 属性?我正在使用 ace.js 库,该库具有与 Dart 的互操作性,该库是我从打字稿接口改编而来的,并且我调用的方法返回带有键值对的纯 JavaScript 对象。
Dart 给了我一个 JsObjectImpl,它不能转换为 Map 或 JsObject,它们都有 [] 访问器。令人困惑的是,它似乎继承自已弃用的 JSObject(注意后者中的“s”大写),它没有 [] 访问器,因此我无法获取数据。
一些错误消息:
尝试从 JsObjectImpl 转换为 JsObject 时:
ORIGINAL EXCEPTION: type 'JSObjectImpl' is not a subtype of type 'JsObject' of 'obj' where
JSObjectImpl is from dart:js
JsObject is from dart:js
。我在使用时收到类似的消息Map
以及。
Looking at the object in the debugger, I can frustratingly see the property in JS view but not in the Dart object:
The 4: Object
is the data I want.
好吧,这很有趣,假期快乐:)
看起来像Map
不支持自动转换package:js
。所以有几件事:
- Filed https://github.com/dart-lang/sdk/issues/28194 https://github.com/dart-lang/sdk/issues/28194
- 已发送给您PR 介绍解决方法 https://github.com/ahirschberg/dart-js-interop-toy/pull/1
对于感兴趣的各方,我们可以使用浏览器原生Object.keys
:
@JS()
library example;
import 'package:js/js.dart';
/// A workaround to converting an object from JS to a Dart Map.
Map jsToMap(jsObject) {
return new Map.fromIterable(
_getKeysOfObject(jsObject),
value: (key) => getProperty(jsObject, key),
);
}
// Both of these interfaces exist to call `Object.keys` from Dart.
//
// But you don't use them directly. Just see `jsToMap`.
@JS('Object.keys')
external List<String> _getKeysOfObject(jsObject);
一旦我们有一个任意的 JavaScript 对象就调用它:
var properties = jsToMap(toy.getData());
print(properties);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)