gpt4 book ai didi

dart - ShadowRoot 没有在 Polymer 中的模板重复中找到元素

转载 作者:行者123 更新时间:2023-12-03 03:11:00 24 4
gpt4 key购买 nike

我在访问 Polymer 元素的 shadowDom 时遇到问题。这是元素的(截断)代码:

<polymer-element name="word-element" attributes="chars">
<template>
<h2>Drag and drop the letters to form anagrams</h2>
<div id='container'>
<div class="char" draggable="true">a</div>
<div class="char" draggable="true">b</div>
<div class="char" draggable="true">c</div>
<br>
<br>
<template repeat="{{chars}}">
<div class="char" draggable="true">{{}}</div>
</template>
</div>
</template>
</polymer-element>

下面是 Dart 代码的样子:

@CustomTag("word-element")
class WordElement extends PolymerElement with ObservableMixin {
@observable List chars;

inserted() {
var charDivs = this.shadowRoot.queryAll('.char');
print(charDivs.length);
}
charDivs.length总是返回 3,计数 3 <div> s 我已经硬编码到 <template> .在 <template repeat="{{chars}}"> 中创建的任何 div使用 shadowRoot 未发现代码.任何想法为什么会这样?

此外,当我将样式应用于具有类 char 的元素时, 样式适用于所有 <div> s,包括在 repeat 中创建的.但是使用 shadowRoot只返回硬编码的 div。

最佳答案

为此,您可以使用 Mutation Observers。正如其他地方所提到的,模板绑定(bind)和重复是在创建和插入自定义元素之后的某个时间异步发生的。

当节点或其子树被修改时,使用 Mutation Observer 得到通知。

这是 Dart 代码:

import 'package:polymer/polymer.dart';
import 'dart:html';
import 'dart:async';

@CustomTag("my-element")
class MyElement extends PolymerElement with ObservableMixin {
final List<String> timestamps = toObservable([]);
MutationObserver observer;

created() {
super.created();

observer = new MutationObserver(_onMutation);
observer.observe(shadowRoot.query('#timestamps'), childList: true, subtree: true);

new Timer.periodic(const Duration(seconds: 1), (t) {
timestamps.add(new DateTime.now().toString());
});
}

// Bindings, like repeat, happen asynchronously. To be notified
// when the shadow root's tree is modified, use a MutationObserver.

_onMutation(List<MutationRecord> mutations, MutationObserver observer) {
print('${mutations.length} mutations occurred, the first to ${mutations[0].target}');
}
}

这是HTML代码:

<polymer-element name="my-element">
<template>
<ul id="timestamps">
<template repeat="{{ts in timestamps}}">
<li>{{ts}}</li>
</template>
</ul>
</template>
<script type="application/dart" src="my_element.dart"></script>
</polymer-element>

关于dart - ShadowRoot 没有在 Polymer 中的模板重复中找到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18686265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com