【问题标题】:How to call a Dart function from Javascript?如何从 Javascript 调用 Dart 函数?
【发布时间】:2014-03-23 01:53:50
【问题描述】:

我想从 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 : method not found: 'Symbol("call")' Receiver: Instance of '(){this.$initialize' Arguments: [Instance of 'Window', 2, 3]

【问题讨论】:

标签: dart dart2js


【解决方案1】:

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

js.context['myHyperSuperMegaFunction'] = myHyperSuperMegaFunction;

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

【讨论】:

    猜你喜欢
    • 2014-05-31
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 2018-06-22
    相关资源
    最近更新 更多