我正在尝试确定建立跨组件通信的最佳方法。我的第一个想法是使用带有通配符的ractive.fire
,但这似乎不起作用。我试图误用ractive.fire吗?与ractive进行跨组件通信的建议方法是什么?
Ractive.components.pubSub = Ractive.extend({
oninit() {
this.on('*.customEvent', () => alert('pub sub got your custom event!'))
}
})
Ractive.components.something = Ractive.extend({
template: '#something'
})
let ractive = new Ractive({
target: 'body',
template: '#app'
})
<script src="https://cdn.jsdelivr.net/npm/ractive@0.10.3/ractive.js"></script>
<script id="app" type="text/ractive">
<pubSub />
<something />
</script>
<script id="something" type="text/ractive">
<button on-click="@.fire('customEvent')">Fire Custom Event</button>
</script>
答案 0 :(得分:1)
Ractive没有规定数据共享/跨组件通信的约定。但是,它确实为您提供了设施。我见过的一个常见做法是创建一个虚拟实例&#34;并使用其ractive.fire()
和ractive.on()
方法。
// The dummy instance, make it visible to components.
const pubsub = Ractive()
const SourceComponent = Ractive.extend({
template: '<button click="send()">Click me</button>',
send(){
pubsub.fire('message')
}
})
const ListeningComponent = Ractive.extend({
onInit(){
pubsub.on('message', () => {
console.log('called')
})
}
})
或者,如果你想要的只是在所有组件之间共享状态,在任何你想要的地方修改它们,并让所有人在更改时重新渲染,你可以将该状态放在@shared
中。