How to map a Dart class to a JS “class” with the new js 0.6.0 package?

南笙酒味 提交于 2019-12-21 21:00:29

问题


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);
}

Just adding the @Js() annotation results in

Exception: 'dart:js': Failed assertion: line 393: 'p.isNamed' is not true. Observatory listening at http://127.0.0.1:35293/ Internal error: Dart_Invoke expects library argument 'target' to be loaded.

Update removing external factory Apple(String type); fixes the exception.

Now I get

Observatory listening at http://127.0.0.1:38029/
red Macintosh apple
Exception: Class 'Apple' has no instance method 'getInfo'.

NoSuchMethodError: method not found: 'getInfo'
Receiver: Instance of 'Apple'
Arguments: [...]
Apple.getInfo
main


回答1:


The class needs a constructor delcaration but without factory

with this 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>

and this Dart code

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);
}

it's working as expected.



来源:https://stackoverflow.com/questions/33168767/how-to-map-a-dart-class-to-a-js-class-with-the-new-js-0-6-0-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!