从Dart中的JavaScript对象获取任意属性 [英] Getting an arbitrary property from a JavaScript object in Dart
问题描述
编辑:
4:对象
是我想要的数据。
好,这是一个有趣的节日快乐:)
它看起来像地图对于
package:js
,不支持code>自动转换。所以有几件事:
对于感兴趣的参与者,我们可以使用浏览器本地的 Object.keys
:
@JS()
库示例;
导入 package:js / js.dart;
///一种将对象从JS转换为Dart Map的解决方法。
Map jsToMap(jsObject){
返回新Map.fromIterable(
_getKeysOfObject(jsObject),
值:(key)=> getProperty(jsObject,key),
);
}
//这两个接口都可以从Dart调用Object.keys。
//
//但是您不能直接使用它们。只需看jsToMap`。
@JS('Object.keys')
外部列表< String> _getKeysOfObject(jsObject);
在我们拥有任意JavaScript对象后调用它:
var属性= jsToMap(toy.getData());
print(properties);
Edit: Here is a minimal project that illustrates my issue. You can see the error described by serving it to the browser: pub get
and then either pub serve
(dartium) or pub build --mode=debug
(other browsers).
How can I access an arbitrary JavaScript property from Dart through a JsObjectImpl? I am using the ace.js library with an interop to Dart that I've adapted from a typescript interface, and the method I am calling returns a plain javascript object with key-value pairs.
Dart gives me a JsObjectImpl, which cannot be casted to a Map or a JsObject, both of which have [] accessors. It confusingly seems to inherit from the deprecated JSObject (note the 's' is capitalized in the latter) which does not have the [] accessor, so I can't get the data out.
Some error messages:
When attempting a cast from JsObjectImpl to 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
. I get a similar message when usingMap
as well.Looking at the object in the debugger, I can frustratingly see the property in JS view but not in the Dart object:
The4: Object
is the data I want.
Ok, this was a fun one, happy holidays :)
It looks like Map
is not a supported auto-conversion for package:js
. So a couple of things:
- Filed https://github.com/dart-lang/sdk/issues/28194
- Sent your a PR introducing a workaround
For interested parties, we can use the browser-native 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);
And call it once we have an arbitrary JavaScript object:
var properties = jsToMap(toy.getData());
print(properties);
这篇关于从Dart中的JavaScript对象获取任意属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!