如何从Javascript中调用Dart函数?

7
我希望能够从Javascript中调用Dart函数。
我想使用dart2js(版本1.1.3)编译包含Dart函数的Dart脚本,然后将生成的.js文件加载到Javascript环境中,并从Javascript中调用该函数。
类似于从Javascript中调用下面的myHyperSuperMegaFunction。
import 'dart:js' as js;

int myHyperSuperMegaFunction(int a, int b) {
  return a + b;
}

main() {
  js.context['myHyperSuperMegaFunction'] = new js.JsFunction.withThis(myHyperSuperMegaFunction);
}

我尝试使用dart2js编译以上内容,并将生成的.js文件加载到Chrome中。变量myHyperSuperMegaFunction已经被注册并定义为:

function () {
    return _call(f, captureThis, this, Array.prototype.slice.apply(arguments));
}

然而,当我从Chrome Javascript控制台调用myHyperSuperMegaFunction(2,3)时,我会收到以下错误:NoSuchMethodError:找不到方法:'Symbol("call")' Receiver: Instance of '(){this.$initialize' Arguments: [Instance of 'Window', 2, 3]


这个回答解决了你的问题吗?如何在Dart语言中创建一个全局(在窗口上)对象? - ggorlen
1个回答

6
您不需要使用new js.JsFunction.withThis。在您的情况下,只需使用:

js.context['myHyperSuperMegaFunction'] = myHyperSuperMegaFunction;

供您参考,当您需要使用Js上下文中的this时,必须使用new js.JsFunction.withThis。在您的错误信息中,您可以看到第一个参数是Instance of 'Window',它是Js中的全局上下文。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接