简体   繁体   English

飞镖映射用作节点互操作的构造函数

[英]Dart mapping Function as constructor with node interop

I've recently started with development in Dart. 我最近开始在Dart中进行开发。 I need to run Dart on the node vm. 我需要在节点vm上运行Dart。 Currently, I am required to create an interop to an external node module. 当前,我需要创建一个到外部节点模块的互操作程序。

This module only exposes constructor functions. 该模块仅公开构造函数。 I am unable to find a way to create a Dart class that maps to a package. 我找不到创建映射到包的Dart类的方法。

Assuming the following node module export: 假设导出以下节点模块:

{
  Client: [Function: Client],
  Server: [Function: Server]
}

In this scenario I am trying to create a new instance of Client in my Dart workspace. 在这种情况下,我试图在Dart工作区中创建Client的新实例。 I've created the following anonymous classes: 我创建了以下匿名类:

@JS()
@anonymous
abstract class ClientImpl {
  // ClientImpl(String, num);
  external String get host;
  external num get port;
}

@JS()
@anonymous
abstract class Module {
  ClientImpl Client(String, num);
}

Now I want to map the Module class to the node module 现在我想将Module类映射到节点模块

final Module _module = require('...');

void main() {
  final client = _module.Client('192.168...', 1234);
}

No typing errors are shown by the analyzer and Dart compiles correctly to Javascript using dart2js. 分析器不会显示任何键入错误,并且Dart使用dart2js可以正确编译为Javascript。 Now when I run my compiled js file in the node VM I get an exception on creating a new instance of Client. 现在,当我在节点VM中运行编译的js文件时,在创建Client的新实例时会出现异常。 It requires the new keyword. 它需要new关键字。 When I manually add the new keyword in the compiled js file I can properly instantiate the interop class. 当我在已编译的js文件中手动添加new关键字时,我可以正确地实例化interop类。

I've also tried to use a typedef instead, but that didnt book any success at all. 我也尝试过使用typedef来代替,但这根本没有取得任何成功。

typedef ClientFunc = ClientImpl Function(String, num);

I can't find any examples online which describe my specific scenario. 我在网上找不到任何描述我的具体情况的示例。 Is there anyone here who has had the same problem or know what I am doing wrong here? 这里有人遇到同样的问题或知道我在做什么错吗?

Thanks in advance 提前致谢

This isn't exactly an answer my the question, but I am using a workaround for now.. 这不完全是我的问题的答案,但是我现在正在使用一种解决方法。

const { Client, Server } = require('...')

module.exports = {
  Client: (hostAddr, port) => new Client(hostAddr, port),
  Server: (...args) => new Server(...args)
}

Now a normal function is exposed instead of a constructor function. 现在公开了一个普通函数而不是构造函数。 However, there must be a way to solve the above without having to write a proxy for it as this one. 但是,必须有一种方法可以解决上述问题,而不必为此编写代理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM