全局 pub-sub/event-handling 在 ractive

global pub-sub/event-handling in ractive

我正在尝试确定建立跨组件通信的最佳方式。我的第一个想法是使用 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>

Ractive 没有规定数据 sharing/cross-component 通信的约定。但是,它确实为您提供了执行此操作的便利。我见过的一种常见做法是创建 "dummy instance" 并使用其 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