JsFunction.apply does not work, while JsObject.callMethod works (dart)

It often happens to me that JsFunction.apply does not work as I expected. Consider this example:

import "dart:js";
import "dart:html";

void main() {
  var div = querySelector('div');
  var span = new SpanElement()..text = "hello world";
  var js = new JsObject.fromBrowserObject(div);
  js["appendChild"].apply([span]);

  // this one does work:
  // js.callMethod("appendChild", [span]);
}

I would expect it js["appendChild"].apply([span]);to work exactly the same as js.callMethod("appendChild", [span]);.

See also this demo: https://dartpad.dartlang.org/0f35d76a3c61ba1371f1

+4
source share
1 answer

He works with js["appendChild"].apply([span], thisArg: js);

If you do not provide thisArg, as you call Function.prototype.apply with nullas the first argument.

So your Dart call is the same as js:

var div = document.querySelector('div');
var span = document.createElement("span");
span.innerText = "hello world";
div["appendChild"].apply(null, [span]);

js TypeError: Illegal invocation. , div["appendChild"].apply(div, [span]);.

, , js.

+4

All Articles