从Dart Code调用匿名Javascript函数

Calling anonymous Javascript function from Dart Code

本文关键字:Javascript 函数 调用 Dart Code      更新时间:2024-03-03

我正在编写一个从JavaScript调用的Dart库,完成后,Dart需要调用JavaScript中的匿名回调函数。

JavaScript:

function main() {
    application.log("ready");
}
function getValueById(id){
    return document.getElementById(id).value;
}
function contact(){
    application.log("Contact Submit Clicked");
    application.contact({
        name: getValueById("contactFormName"),
        email: getValueById("contactFormEmail"),
        phone: getValueById("contactFormPhone"),
        message: getValueById("contactFormMessage"),
        subject: "Message From " + getValueById("contactFormName") + " via Contact Form",
        callback: function(response){
            // TODO: handle response here
            console.log("callback being executed");
            console.log(response);
        }
    });
}
var application = function () {
    this.companyId = "5905063580";
    this.companyName = "Company XYZ";
    this.ready = main;
}

HTML:

....
<button onclick="contact()">Submit</button>

Dart:

import 'dart:html';
import 'dart:js';
...
contact(ContactRequest request, callback)  {
  new RPC.submit(request, URL.contactURL, request.companyName, (res) {
    ContactResponse response = new ContactResponse();
    response.fromJson(res);
    print(response.toString());        
    // prints {"message":"Message Sent", ...}
    // do callback here
    // context.callMethod(callback, [response]); <-- failing here
    // callback(response); <-- also failing

  });
}
void main() {
  String companyId = null;
  String companyName = null;
  context['application']['log'] = (String param) {
    print(param);
  };
  context['application']['contact'] = (JsObject param) {
    ContactRequest request = new ContactRequest();
    request.companyId = companyId;
    request.companyName = companyName;
    request.action = "CONTACT";
    request.name = param["name"];
    request.email = param["email"];
    request.phone = param["phone"];
    request.message = param["message"];
    request.subject = param["subject"];
    contact(request, param["callback"]);
  };
  ...
  var application = new JsObject(context['application']);
  companyId = application['companyId'];
  companyName = application["companyName"];
  application.callMethod("ready");
}

JavaScript成功地调用了Dart方法联系人,Dart成功地与Java后端通信,Java后端用Json进行响应,现在最后一步是Dart调用发送给它的回调,这就是它失败的地方,也是我不知道如何使它工作的地方。

如果我回调(响应),这是我得到的异常:

Exception: Uncaught Error: Class 'JsFunction' has no instance method 'call'.
NoSuchMethodError: method not found: 'call'
Receiver: Instance of 'JsFunction'
Arguments: [Instance of 'ContactResponse']
Stack Trace:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:45)
#1      contact.<anonymous closure> (http://localhost:63342/jsapi/web/cloudauctioneers.v1.dart:24:13)
#2      RPC.RPC.submit.<anonymous closure> (package:jsapi/model/rpc.dart:10:17)
#3      _RootZone.runUnary (dart:async/zone.dart:1155)
#4      _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:484)
#5      _Future._propagateToListeners (dart:async/future_impl.dart:567)
#6      _Future._completeWithValue (dart:async/future_impl.dart:358)
#7      _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:412)
#8      _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#9      _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#10     _handleMutation (dart:html:41819)
 undefined:1undefined

这也会失败:JsFunction.callMethod(callback, [response]);

Exception: Uncaught Error: No static method 'callMethod' declared in class 'JsFunction'.
NoSuchMethodError: method not found: 'callMethod'
Receiver: Type: class 'JsFunction'
Arguments: [Instance of 'JsFunction', Instance(length:1) of '_GrowableList']
Stack Trace:
#0      NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:173)
#1      contact.<anonymous closure> (http://localhost:63342/jsapi/web/cloudauctioneers.v1.dart:26:16)
#2      RPC.RPC.submit.<anonymous closure> (package:jsapi/model/rpc.dart:10:17)
#3      _RootZone.runUnary (dart:async/zone.dart:1155)
#4      _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:484)
#5      _Future._propagateToListeners (dart:async/future_impl.dart:567)
#6      _Future._completeWithValue (dart:async/future_impl.dart:358)
#7      _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:412)
#8      _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#9      _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#10     _handleMutation (dart:html:41819)

我认为您需要调用类似的JavaScript函数

callback.apply([response]);

这样你就无法通过Response。您只能传递基元值或基元值的集合,如:

Map arg = {'message': response.message, 'otherfield': response.otherField};
callback.apply([new JsObject.jsify(arg)]);