如何从JavaScript调用Dart函数? [英] How to call a Dart function from Javascript?

查看:119
本文介绍了如何从JavaScript调用Dart函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Javascript中调用Dart函数。

I would like to call a Dart function from Javascript.

我想编译一个包含Dart函数的Dart脚本,使用 dart2js (版本1.1.3),然后将生成的 .js 文件加载到Javascript环境中,并从Javascript中调用该函数。

I would like to compile a Dart script containing a Dart function using dart2js (version 1.1.3) and then load the generated .js file into a Javascript environment and call that function from Javascript.

以下来自Javascript的调用 myHyperSuperMegaFunction 的行为。

Something along the lines of calling myHyperSuperMegaFunction below from Javascript.

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 已注册并定义为

I tried compiling the above with dart2js and loading the generated .js file into Chrome. Variable myHyperSuperMegaFunction is registered and defined as

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


$ b < )从Chrome JavaScript控制台我收到以下错误 NoSuchMethodError:method not found:'Symbol(call)'Receiver:Instance of'(){this。$ initialize'参数:[Instance of'Window',2,3]

However, when I call myHyperSuperMegaFunction(2,3) from Chrome Javascript console I get the following error NoSuchMethodError : method not found: 'Symbol("call")' Receiver: Instance of '(){this.$initialize' Arguments: [Instance of 'Window', 2, 3]

推荐答案

使用 new js.JsFunction.withThis 。在你的情况下只需使用:

You don't need to use new js.JsFunction.withThis. In your case just use :

js.context['myHyperSuperMegaFunction'] = myHyperSuperMegaFunction;

有关您的信息 new js.JsFunction.withThis 必须在需要使用 this Js上下文时使用。在你的错误中,你可以看到第一个参数是'Window'的实例这是Js中的全局上下文。

For your information new js.JsFunction.withThis has to be used when you need to use the this Js context. In your error, you can see that the first parameter is Instance of 'Window' which is the global context in Js.

这篇关于如何从JavaScript调用Dart函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆