Skip to content

Instantly share code, notes, and snippets.

@johnnypez
Last active August 29, 2015 14:10
Show Gist options
  • Save johnnypez/5c1064e99bdc5e77d7b6 to your computer and use it in GitHub Desktop.
Save johnnypez/5c1064e99bdc5e77d7b6 to your computer and use it in GitHub Desktop.
This is a trivial example of how we connect stores with react components. I'd love to hear any thoughts or feedback on how we handle store versioning, listening etc.
define (require) ->
FooStore = require './foo_store'
ListeningMixin = require './listening_mixin'
_getStateFromStores = ->
ver: FooStore.ver()
foo: FooStore.foo()
React.createClass
mixins: [ListeningMixin]
getInitialState: -> _getStateFromStores()
componentDidMount: ->
@listenTo FooStore, => @setState _getStateFromStores()
# we do this in cases where we need fine control over
# when views update
shouldComponentUpdate: (nextProps, nextState) ->
nextState.ver != @state.ver
render:
`<div>{this.state.foo}</div>`
define (require) ->
StoreFactory = require './store_factory'
_foo = 'foo'
store = StoreFactory.create
foo: -> _foo
store.dispatchToken = Dispatcher.register (action) ->
switch action.name
when 'foo_store.update_foo'
_foo = action.payload
store.changed()
define (require) ->
# this mixin makes it easy for us to bind and unbind to store change
# events as the component mounts and unmounts
ListeningMixin =
listenTo: (store, callback)->
Backbone.Events.listenTo.call(this, store, 'change', callback)
componentWillUnmount: ->
Backbone.Events.stopListening.call(this)
define ->
createStore = (methods) ->
_.extend {}, methods, Backbone.Events,
__ver__: 1
ver: -> @__ver__
changed: ->
@__ver__++
@trigger 'change'
onChange: (callback) -> @on 'change', callback
return create: createStore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment