Flux Architecture แบบง่ายด้วย Vue.js
สำหรับแอปเล็ก ๆ ที่ต้องการแค่ pattern จัดการ state แบบง่าย ๆ ผู้เขียนมักใช้ component เดียวเก็บ state ของแอปไว้ เรียกว่า container ซึ่งทำหน้าที่เป็น single source of truth ให้แอปใช้อ้างอิง state ของตัวเอง Vue มีกลไกสำหรับสร้าง global event listener ที่ระดับ root เรียกว่า EventBus ซึ่งเป็นวิธีสุดง่ายในการเลียนแบบ Flux Architecture
ทั้งหมดที่คุณต้องมีคือ module เดียวที่ export Vue เป็น EventBus แบบนี้
// EventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
จากนั้นใช้ EventBus ใน container เพื่อ listen event จาก component ไหนก็ได้ในแอป ปกติผู้เขียนจะเพิ่ม listener ไว้ใน life cycle created
EventBus.$on('event-name', callback)
จากนั้น import EventBus เข้าไปใน component ไหนก็ได้ แล้ว trigger my-custom-event จากตรงไหนก็ได้ ไม่ต้อง emit event ขึ้นไปหา parent แล้วทำซ้ำแบบเดิมในทุก component ที่คั่นอยู่ระหว่าง component ต้นทางกับ container ปลายทาง
// Goes directly to the global listener and triggers callback
EventBus.$emit('event-name')
แค่นั้นเลย ถ้ามันเริ่มซับซ้อนเกินไป ลองพิจารณาใช้ Vuex