Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

JrSchild commented Oct 26, 2016

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
You can’t perform that action at this time.