1

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

接下来我希望 JavaScript 函数“onKey”将调用 Dart 函数“callbackFromJs”再次将控制权返回给 Dart(成功或异常)。

你能帮我完成这个完整的流程吗?请假设每个边界都成功例外——我不能依赖第 3 方代码——DART 2 JS 2 DART?


为了为这个一般问题提供更多背景信息,我放置了示例代码。

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);
}
4

1 回答 1

2

First have a look at Using JavaScript from 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');
  }
}

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

于 2014-02-10T08:11:56.190 回答