简体   繁体   English

如何在稳定的1.1.1 Dart中绑定JavaScript回调并在JavaScript(Dart2Js2Dart)中绑定Dart回调?

[英]How to bind JavaScript callback in stable 1.1.1 Dart and bind Dart callback in JavaScript (Dart2Js2Dart)?

I want to write some Dart function "oKey" which calls JavaScript function "jsOnKey" (with success or exception too since cannot predict). 我想编写一些Dart函数“ oKey”,该函数调用JavaScript函数“ jsOnKey”(因为无法预测,所以也会成功或异常)。

Next I want that JavaScript function "onKey" will call Dart function "callbackFromJs" to return control to Dart again (with success or exception). 接下来,我希望JavaScript函数“ onKey”将调用Dart函数“ callbackFromJs”,以再次将控制权返回给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? 您能否为我提供全部帮助-请在每个边界上假设成功例外 -我不能依靠第三者代码-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);
}

First have a look at Using JavaScript from Dart . 首先看一下Dart中的Using JavaScript

For your case you can simply pass callbacks to handle what you call Js 2 Dart : 对于您的情况,您可以简单地传递回调来处理您所谓的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');
  }
}

The Dart exceptions can be catch with the same kind of code on Js side. 可以在Js端使用相同类型的代码捕获Dart异常。

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

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