为了从孩子到父母进行交流,事件似乎是最优雅的方式。父母与孩子沟通的方式有哪些?
更具体地说,我想要一个在孩子可见时调用的方法。这些是我提出的想法:
- xtag - 优雅而有效
- 观察“隐藏” - 无法使其正常工作,隐藏在元素中未标记为可观察
- 在子级中发布触发变量,在父级中绑定和更改它 - 丑陋
还有其他选择吗?
为了从孩子到父母进行交流,事件似乎是最优雅的方式。父母与孩子沟通的方式有哪些?
更具体地说,我想要一个在孩子可见时调用的方法。这些是我提出的想法:
还有其他选择吗?
我还没有尝试过,但也许MutationObserver 可以满足您的要求。
Seth Ladd 的聚合物示例包含两个示例:第一个监听 onMutation 事件 https://github.com/sethladd/dart-polymer-dart-examples/blob/master/web/onmutation-mutation-observer/my_element.dart
library my_element;
import 'package:polymer/polymer.dart';
import 'dart:html';
import 'dart:async';
@CustomTag('my-element')
class MyElement extends PolymerElement {
MyElement.created() : super.created() {
// NOTE this only fires once,
// see https://groups.google.com/forum/#!topic/polymer-dev/llfRAC_cMIo
// This is useful for waiting for a node to change in response
// to some data change. Since we don't know when the node will
// change, we can use onMutation.
onMutation($['list']).then((List<MutationRecord> records) {
$['out'].text = 'Change detected at ${new DateTime.now()}';
});
new Timer(const Duration(seconds:1), () {
$['list'].children.add(new LIElement()..text='hello from timer');
});
}
}
第二个示例使用 MutationObserver 类 https://github.com/sethladd/dart-polymer-dart-examples/blob/master/web/mutation_observers/my_element.dart
=== 编辑 ===
您是否尝试过链接的示例?观察方法允许指定应该观察什么:
/**
* Observes the target for the specified changes.
*
* Some requirements for the optional parameters:
*
* * Either childList, attributes or characterData must be true.
* * If attributeOldValue is true then attributes must also be true.
* * If attributeFilter is specified then attributes must be true.
* * If characterDataOldValue is true then characterData must be true.
*/
void observe(Node target,
{bool childList,
bool attributes,
bool characterData,
bool subtree,
bool attributeOldValue,
bool characterDataOldValue,
List<String> attributeFilter}) {
为了从母聚合物到子聚合物进行通信,这个解决方案对我很有用。
如果我们有一个像这样的子聚合物元素:
library my_element;
import 'package:polymer/polymer.dart';
import 'dart:html';
import 'dart:async';
@CustomTag('my-element')
class MyElement extends PolymerElement {
MyElement.created() : super.created() {
}
myCustomMethod(param){
print("pass-in param = $param");
}
}
要从父元素访问您的子元素:
(theParentClass.querySelector("my-element") as MyElement).myCustomMethod({"done":true});