如何使用新的js 0.6.0包将Dart类映射到JS“类”?

时间:2015-10-16 10:55:45

标签: dart dart-js-interop

的index.html

<!doctype html>
<html>
  <head>
  </head>
    <script>
      var Apple = function(type) {
        this.type = type;
        this.color = "red";
      };

      Apple.prototype.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
      };
    </script>
  <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 'dart:html' as dom;
import 'package:js/js.dart';

main() {
  // this works fine
  var apple = new js.JsObject(js.context['Apple'], ['Macintosh']);
  print(apple.callMethod('getInfo', []));
  print(new Apple().getInfo());
}

@Js() // about to being changed to @JS
class Apple {
  external String get type;
  external set type(String type);
  external String get color;
  external set color(String color);
  external factory Apple(String type);
}

只需添加@Js()注释结果

即可
  

异常:'dart:js':断言失败:第393行:'p.isNamed'不正确。   天文台在http://127.0.0.1:35293/听   内部错误:Dart_Invoke期望加载库参数'target'。

更新 删除external factory Apple(String type);可修复异常。

现在我

  

天文台在http://127.0.0.1:38029/聆听   红色Macintosh苹果
  例外:类'Apple'没有实例方法'getInfo'。

     

NoSuchMethodError:找不到方法:'getInfo'
  接收者:'Apple'的实例   论点:[...]
    Apple.getInfo
    主要

1 个答案:

答案 0 :(得分:3)

该类需要构造函数说明但没有factory

用这个JS

<script>
  var Apple = function(type) {
    this.type = type;
    this.color = "red";
    this.getInfo2 = function() {
      return this.color + ' ' + this.type + ' apple';
    };
  };

  Apple.prototype.getInfo = function() {
    return this.color + ' ' + this.type + ' apple';
  };
</script>

和这个Dart代码

main() {
  var apple = new js.JsObject(js.context['Apple'], ['Macintosh']);
  print(apple.callMethod('getInfo', []));
  print(new Apple('Macintosh').type);
  print(new Apple('Macintosh').getInfo2());
  print(new Apple('Macintosh').getInfo());
}

@Js() // about to being changed to @JS
class Apple {
  external String get type;
  external set type(String type);
  external String get color;
  external set color(String color);
  external String getInfo();
  external String getInfo2();
  external Apple(String type);
}

它按预期工作。