How to map a Dart class to a JS “class” with the n

2019-04-13 01:01发布

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条回答
叛逆
2楼-- · 2019-04-13 01:39

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.

查看更多
登录 后发表回答