I have this often, that JsFunction.apply doesn't work like I would expect. Consider this example:
我经常这样,JsFunction.apply不能像我期望的那样工作。考虑这个例子:
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 that js["appendChild"].apply([span]);
to work exactly the same as js.callMethod("appendChild", [span]);
.
我希望js [“appendChild”]。apply([span]);与js.callMethod完全相同(“appendChild”,[span]);.
See also this demo: https://dartpad.dartlang.org/0f35d76a3c61ba1371f1
另请参见此演示:https://dartpad.dartlang.org/0f35d76a3c61ba1371f1
1 个解决方案
#1
4
It works with js["appendChild"].apply([span], thisArg: js);
它适用于js [“appendChild”]。apply([span],thisArg:js);
If you don't provide thisArg
it's like you call Function.prototype.apply with null
as first argument.
如果你不提供thisArg,就像调用Function.prototype.apply一样,将null作为第一个参数。
Thus your Dart call is the same as the js :
因此你的Dart调用与js相同:
var div = document.querySelector('div');
var span = document.createElement("span");
span.innerText = "hello world";
div["appendChild"].apply(null, [span]);
The execution of above js code leads to a TypeError: Illegal invocation
. To make it work you have to use div["appendChild"].apply(div, [span]);
.
上面的js代码的执行导致TypeError:非法调用。要使它工作,你必须使用div [“appendChild”]。apply(div,[span]);.
So it was not a Dart issue but rather a js issue.
所以这不是Dart问题,而是js问题。
#1
4
It works with js["appendChild"].apply([span], thisArg: js);
它适用于js [“appendChild”]。apply([span],thisArg:js);
If you don't provide thisArg
it's like you call Function.prototype.apply with null
as first argument.
如果你不提供thisArg,就像调用Function.prototype.apply一样,将null作为第一个参数。
Thus your Dart call is the same as the js :
因此你的Dart调用与js相同:
var div = document.querySelector('div');
var span = document.createElement("span");
span.innerText = "hello world";
div["appendChild"].apply(null, [span]);
The execution of above js code leads to a TypeError: Illegal invocation
. To make it work you have to use div["appendChild"].apply(div, [span]);
.
上面的js代码的执行导致TypeError:非法调用。要使它工作,你必须使用div [“appendChild”]。apply(div,[span]);.
So it was not a Dart issue but rather a js issue.
所以这不是Dart问题,而是js问题。