Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Element.replaceChildren(node1, node2, node3, ...nodes) / how to use Function.apply ? #292

Open
jonasfj opened this issue Aug 26, 2024 · 2 comments
Labels
type-question A question about expected behavior or functionality

Comments

@jonasfj
Copy link
Member

jonasfj commented Aug 26, 2024

In JS we can do:

containerForValues.replaceChildren(...values.map((value) => {
  const element = document.createElement('div');
  element.innerHTML = value;
  return element;
}));

In Dart we I tried using:

containerForValues.replaceChildren(
  values
      .map(
        (value) => HTMLDivElement()
          ..setHTMLUnsafe(value),
      )
      .toList()
      .toJS,
);

But this doesn't work, because the first argument can't be a list. So the list is converted to a String. Do my containerForValues ends up showing:

[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement]

:D

@ykmnkmi
Copy link

ykmnkmi commented Aug 26, 2024

Using dart:js_interop_unsafe:

import 'dart:js_interop';
import 'dart:js_interop_unsafe';

import 'package:web/web.dart';

void main() {
  var container = document.querySelector('body') as Element;
  container.callMethodVarArgs('replaceChildren'.toJS, [/* ... */]);
}

Without:

import 'dart:js_interop';

import 'package:web/web.dart';

void main() {
  var container = document.querySelector('body') as Element;
  container.jsReplaceChildren.apply(container, <JSAny?>[/* */].toJS);
}

extension on Element {
  @JS('replaceChildren')
  external JSFunction get jsReplaceChildren;
}

extension on JSFunction {
  external R apply<R extends JSAny?>(JSAny? thisArgument, JSArray<JSAny?> arguments);
}

@srujzs srujzs added the type-question A question about expected behavior or functionality label Aug 27, 2024
@srujzs
Copy link
Contributor

srujzs commented Aug 27, 2024

@ykmnkmi nailed it. callMethodVarArgs is ultimately a JS Function.apply call, so the end result is the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type-question A question about expected behavior or functionality
Projects
None yet
Development

No branches or pull requests

3 participants