如何绑定JavaScript回调在稳定1.1.1 Dart和绑定Dart回调在JavaScript(Dart2Js2Dart)? [英] How to bind JavaScript callback in stable 1.1.1 Dart and bind Dart callback in JavaScript (Dart2Js2Dart)?

查看:459
本文介绍了如何绑定JavaScript回调在稳定1.1.1 Dart和绑定Dart回调在JavaScript(Dart2Js2Dart)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一些Dart函数oKey,它调用JavaScript函数jsOnKey(成功或异常,因为无法预测)。

I want to write some Dart function "oKey" which calls JavaScript function "jsOnKey" (with success or exception too since cannot predict).

JavaScript函数onKey将调用Dart函数callbackFromJs将控制权返回到Dart(成功或异常)。

Next I want that JavaScript function "onKey" will call Dart function "callbackFromJs" to return control to Dart again (with success or exception).

你能帮助我完成这个流程吗在每个边框上假设 SUCCESS EXCEPTION - 我不能依赖第三方代码 - DART 2 JS 2 DART?

Can you help me with this full flow - please assume SUCCESS or EXCEPTION on each border - I can not rely on 3rd party code - DART 2 JS 2 DART?

为了给这个一般问题更多的上下文,我把示例代码。

To make more context to this general question I put example code.

import 'dart:html';

void onKey(Event event) {
  // I want to call something in javascript
  // function callbackFromDart () { 
  //  /* something */; 
  //  /* call callbackJs in Dart - return control to dart */
  // }
}

void callbackFromJs() {
  // It should be called from JavaScript
}

void main() {
  InputElement nameElement = querySelector('input[name=name]');
  nameElement..placeholder = 'Enter text'
      ..onKeyUp.listen(onKey);

  InputElement descriptionElement = querySelector('input[name=description]');
  descriptionElement..placeholder = 'Enter text'
    ..onKeyUp.listen(onKey);
}


推荐答案

a href =https://www.dartlang.org/articles/js-dart-interop/ =nofollow>使用Dart中的JavaScript 。

First have a look at Using JavaScript from Dart.

对于您的情况,您可以简单地传递回调以处理您调用的 Js 2 Dart

For your case you can simply pass callbacks to handle what you call Js 2 Dart :

import 'dart:js' as js;

void onKey(Event event) {
  onSuccess() {
    // Dart callback called from Js
  }
  onError() {
    // Dart callback called from Js
  }

  // assuming your js function takes 2 callbacks as parameters
  try {
    // in JS : function a() { throw "throw from js"; }
    js.context.callMethod('myTopLevelFunction', [onSuccess, onError]);
  } 
  catch (e) {
    print('js error catch on Dart side : $e');
  }
}

Dart异常可以用同一种Js端的代码。

The Dart exceptions can be catch with the same kind of code on Js side.

这篇关于如何绑定JavaScript回调在稳定1.1.1 Dart和绑定Dart回调在JavaScript(Dart2Js2Dart)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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