如何使用新的 js (0.6.0) 包调用 JS 函数
How to call a JS function with the new js (0.6.0) package
index.html
<!doctype html>
<html>
<head>
<script>
var testFunction = function() {return 'xxx'};
</script>
</head>
<body>
<script type="application/dart" src="index.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
index.dart
import 'dart:js' as js;
import 'package:js/js.dart';
@Js() // about to being changed to @JS
external String testFunction();
main() {
// fails: Exception: Uncaught Error: No top-level method 'testFunction' declared.
print(testFunction());
// works
print((js.context['testFunction'] as js.JsFunction).apply([]));
}
Dart VM version: 1.13.0-edge.a598fea28cf26ed82b0a197e65af33a7edca5cac (Thu Oct 15 18:02:15 2015) on "linux_x64"
按预期工作。
我刚刚在 Dart 更新期间使用了 Dartium 运行,并且在尝试该示例时仍然使用旧版本 运行。关闭并重新打开 Dartium 后,代码运行良好。
index.html
<!doctype html>
<html>
<head>
<script>
var testFunction = function() {return 'xxx'};
</script>
</head>
<body>
<script type="application/dart" src="index.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
index.dart
import 'dart:js' as js;
import 'package:js/js.dart';
@Js() // about to being changed to @JS
external String testFunction();
main() {
// fails: Exception: Uncaught Error: No top-level method 'testFunction' declared.
print(testFunction());
// works
print((js.context['testFunction'] as js.JsFunction).apply([]));
}
Dart VM version: 1.13.0-edge.a598fea28cf26ed82b0a197e65af33a7edca5cac (Thu Oct 15 18:02:15 2015) on "linux_x64"
按预期工作。
我刚刚在 Dart 更新期间使用了 Dartium 运行,并且在尝试该示例时仍然使用旧版本 运行。关闭并重新打开 Dartium 后,代码运行良好。