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

若如初见. 提交于 2020-01-06 03:57:05

问题


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

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

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

回答1:


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.



来源:https://stackoverflow.com/questions/21664092/how-to-bind-javascript-callback-in-stable-1-1-1-dart-and-bind-dart-callback-in-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!