我有一个父组件,在“铁页”组件中有两个子组件。当父母收到来自其中一个孩子的事件时,它应该切换页面。问题是,当事件到达父组件时,它执行代码来切换子组件,但没有任何反应。但是,如果代码是在父组件本身上执行的,那么它就可以工作。
我的问题是:为什么子组件发送事件时父组件无法切换页面?
下面是两个子组件的代码:
// this is "child-comm.html"
<link rel="import"
href="bower_components/polymer/polymer.html">
<dom-module id="child-comm">
<style>
div {
width: 300px;
height: 300px;
background-color: #CCC;
}
</style>
<template>
<div>I'm child 0!</div>
</template>
</dom-module>
<script>
Polymer({
is: "child-comm",
listeners: {
'tap': 'doTap'
},
doTap: function() {
this.fire("taped-child")
}
});
</script>
和另一个孩子:
this is "child-comm2.html"
<link rel="import"
href="bower_components/polymer/polymer.html">
<dom-module id="child-comm2">
<style>
div {
width: 300px;
height: 300px;
background-color: #C00;
}
</style>
<template>
<div>I'm child 2!</div>
</template>
</dom-module>
<script>
Polymer({
is: "child-comm2",
listeners: {
'tap': 'doTap'
},
doTap: function() {
this.fire("taped-child")
}
});
</script>
然后我们有父组件:
<link rel="import"
href="bower_components/polymer/polymer.html">
<link rel="import"
href="child-comm.html">
<link rel="import"
href="child-comm2.html">
<link rel="import"
href="bower_components/iron-pages/iron-pages.html">
<dom-module is="parent-comm">
<template>
<iron-pages selected="0">
<child-comm on-taped-child="switchPages"></child-comm>
<child-comm2 on-taped-child="switchPages"></child-comm2>
</iron-pages>
</template>
</dom-module>
<script>
Polymer({
is: "parent-comm",
switchPages: function(e) {
this.pages.selectNext(); // this will not work if the event is created in a child component
console.log(this.pages); // this will print the correct node on console even when being fired by a child custom event
},
ready: function() {
this.pages = document.querySelector('iron-pages');
this.switchPages(); // this will switch pages correctly
console.log(this.pages);
}
});
</script>
谢谢...