【问题标题】:How to map a Dart class to a JS "class" with the new js 0.6.0 package?如何使用新的 js 0.6.0 包将 Dart 类映射到 JS“类”?
【发布时间】:2016-01-15 02:32:00
【问题描述】:

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
主要的

【问题讨论】:

    标签: dart dart-js-interop


    【解决方案1】:

    该类需要一个构造函数声明但没有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);
    }
    

    它按预期工作。

    【讨论】:

      猜你喜欢
      • 2016-01-14
      • 2016-01-15
      • 2018-05-11
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      相关资源
      最近更新 更多