Skip to content

Instantly share code, notes, and snippets.

@stukennedy
Last active April 29, 2019 22:05
Show Gist options
  • Save stukennedy/c605846751c09a5e94d12ae8c91cbf05 to your computer and use it in GitHub Desktop.
Save stukennedy/c605846751c09a5e94d12ae8c91cbf05 to your computer and use it in GitHub Desktop.
Implementing Flux architecture in RiotJS

Implementing Flux architecture in RiotJS

RiotControl seems an unnecessary dependency and has a critical issue whereby registering multiple stores causes any event to be triggered multiple times. I decided to create a minimal dispatcher.

Create a very simple dispatcher singleton called dispatcher.js:

import riot from 'riot'

class Dispatcher {
  constructor () {
    riot.observable(this)
  }
}
export default new Dispatcher()

Now use it in stores like this:

import dispatcher from './dispatcher'

class MyStore {
  constructor () {
    dispatcher.on('my_event', this.foo.bind(this))
  }

  foo () {
    dispatcher.trigger('update_event', 'bar')
  }
}
export default new MyStore()

... and in Tags like this:

import dispatcher from './dispatcher'

<my-tag>
  <h2>{ data }</h2>
  <button onclick={ switch }>Bar</button>
  
  <script>
    this.data = 'foo'
    this.on('mount', () => {
      dispatcher.on('update_event', this.updateEvent)
    })
    this.on('unmount', () => {
      dispatcher.off('update_event', this.updateEvent)
    })
    
    this.switch = () => {
        dispatcher.trigger('my_event')
    }

    this.updateEvent = (data) => {
      this.data = data
      this.update()
    }
  </script>
</my-tag>
@JrSchild
Copy link

It couldn't be more minimal. I love it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment