我希望尝试下一代"下一代" Dart JS互操作的目标是能够导出Dart库以供JS使用。但它似乎并不适合我。我跟着README:
https://github.com/dart-lang/js-interop/blob/master/README.md
我创建了一个新项目,将依赖项设置为此github repo,添加了一个类似于自述文件的A类,并尝试使用控制台从javascript实例化A类。
在控制台中使用默认或命名构造函数时,我得到:
var a = new dart.lib.A.withName('word');
TypeError: undefined is not a function
var a = new dart.lib.A();
TypeError: undefined is not a function
这改写功能了吗?难道我做错了什么?是否应该使用js-interop的不同分支?
这是我自述的简单项目:
## pubspec.yaml
name: lib
description: A sample Dart lib published to JS
dependencies:
browser:
js:
git: git://github.com/dart-lang/js-interop.git
transformers:
- js
- js/initializer
## lib/a.dart
library lib;
import 'package:js/js.dart';
@Export()
class A {
String name;
A();
A.withName(this.name);
}
## web/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index</title>
</head>
<body>
<p id="text"></p>
<script type="application/dart" src="index.dart"></script>
<!-- for this next line to work, your pubspec.yaml file must have a dependency on 'browser' -->
<script src="packages/js/interop.js"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
## web/index.dart
import 'package:lib/a.dart';
import 'package:js/js.dart';
main() {
initializeJavaScript();
var a = new A();
}
## Generated index.dart_initialize.js
window.dart = window.dart || {};
window.dart.Object = function DartObject() {
throw "not allowed";
};
window.dart.Object._wrapDartObject = function(dartObject) {
var o = Object.create(window.dart.Object.prototype);
o.__dart_object__ = dartObject;
return o;
};
// library lib
(function (ns) {
var lib = ns;
["lib"].forEach(function (s) {
lib = lib[s] = lib[s] || {};
});
// class A
(function(parent) {
var constructor = parent.A = function _A() {
this.__dart_object__ = constructor._new();
};
constructor.prototype = Object.create(dart.Object.prototype);
constructor.prototype.constructor = constructor;
constructor._wrapDartObject = function(dartObject) {
var o = Object.create(constructor.prototype);
o.__dart_object__ = dartObject;
return o;
};
constructor.withName = function _withName(name) {
this.__dart_object__ = constructor._new_withName(name);
}
constructor.withName.prototype = constructor.prototype;
})(lib);
})(window.dart);
答案 0 :(得分:3)
我刚试过你的代码,事实上我已经从指令中留下了一些东西。您需要在initializeJavaScript()
方法中调用main()
来设置导出。此外,interop.js
的脚本标记需要在Dart脚本之前。
一旦我做了这些更改,我就可以运行你的代码并在JS控制台中执行此操作:
> var a = new dart.lib.A.withName('word');
< undefined
> a
< _withName {__dart_object__: DartObject, constructor: function}
> a.name
< "word"
> a instanceof dart.lib.A;
< true
答案 1 :(得分:1)
这是一项正在进行中的工作。你必须等到使用它之前。