我有一个父组件,在“iron-pages”组件中有两个子组件。当父级收到来自子级之一的事件时,应该切换页面。问题是,当事件到达父组件时,它执行代码来切换子组件,但没有任何反应。但是,如果代码在父组件本身上执行,那么它就可以工作。
我的问题是:为什么子组件发送事件时父组件无法切换页面?
下面是两个子组件的代码:
// 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>
和另一个 child :
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>
谢谢...
最佳答案
解决这个特殊问题的一个快速技巧是拦截父节点上的子事件,但不让它调用切换页面的方法,而是异步调用该方法。下面是父节点的工作代码:
<dom-module is="parent-comm">
<template>
<iron-pages selected="0">
<child-comm on-taped-child="asyncSwitchPages"></child-comm>
<child-comm2 on-taped-child="asyncSwitchPages"></child-comm2>
</iron-pages>
</template>
</dom-module>
<script>
Polymer({
is: "parent-comm",
switchPages: function() {
this.pages.selectNext();
},
asyncSwitchPages: function(e) {
this.async(this.switchPages);
},
ready: function() {
this.pages = document.querySelector('iron-pages');
}
});
</script>
注意:我很想听听“为什么”我必须这样做,所以我不会接受这个答案。
关于javascript - polymer 1.0 : iron-pages not switching pages with children events,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30685807/