1

Can all objects after js.context be accessed with array notation from Dart? For example, I'd like to convert the following to use array notation:

var request = js.context.gapi.client.request(js.map(requestData));

Will the following array notation work?

var request = js.context['gapi']['client']['request'](js.map(requestData));

Also, should the following be done if trying to access JavaScript builtin methods?

js.context['JSON']['stringify'](jsonResp);

2 Answers 2

4

TL;DR : Starting from r24278 use array notation for properties and noSuchMethod for methods.


Using js.context['gapi']['client'] gives the same result as js.context.gapi.client. The main advantage of Array notation is that it avoids noSuchMethod. Until recently it was the only way to work around an issue in dart2js where minified does not work with noSuchMethod. This issue is fixed, and minification should work with Dart-JS interop.

I did a little benchmark some times ago :

  • For attribute access : array notation is around 10% faster than noSuchMethod. ( js.context.x vs. js.context['x'] )
  • For method access : array notation is around 50% slower than noSuchMethod. ( js.context.f() vs. js.context['f']() )

This last result is explained by 2 communications between JS and Dart for js.context['f'](). One to retrieve the function reference ( js.context['f'] ) and an other to call this function.

Last concern, using noSuchMethod can increase your dart2js result size (but not so much where I had tested it).

1

This works for me:

  var hug = new js.Proxy(context['Hug']);

  var hugDatabase = new js.Proxy(context['HugDatabase']);

  hugDatabase['addHug'](hug);

  print(hugDatabase['hugs']['length']);

Which interacts with this JavaScript:

function Hug(strength) {
  this.strength = strength;
}

Hug.prototype.embrace = function(length) {
  return 'Thanks, that was a good hug for ' + length + ' minutes!';
}

Hug.prototype.patBack = function(onDone) {
  onDone('All done.');
}

function HugDatabase() {
  this.hugs = [];
}

HugDatabase.prototype.addHug = function(hug) {
  this.hugs.push(hug);
}

The full example is here: https://github.com/sethladd/dart-example-js-interop/blob/master/web/dart_js_interop_example.dart

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.