Skip to content

Instantly share code, notes, and snippets.

@mattmccray
Last active June 23, 2016 16:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmccray/d8740ea97013c7505a9b to your computer and use it in GitHub Desktop.
Save mattmccray/d8740ea97013c7505a9b to your computer and use it in GitHub Desktop.
Port of React Mobservable ObserverMixin to Deku
import mob from 'mobservable'
export default function observant( target ) {
let _unsubscriber = null,
_updateCount = 0,
_render = target.render,
_beforeUnmount = target.beforeUnmount
target.render = ( component, setState ) => {
_unsubscriber && _unsubscriber()
let [result, unsubscribe] = mob.watch(
() => _render(component, setState),
() => setState({ __updates: _updateCount++ })
)
_unsubscriber = unsubscribe
return result
}
target.beforeUnmount = ( component, el ) => {
_unsubscriber && _unsubscriber()
_beforeUnmount && _beforeUnmount(component, el)
}
// If there's already a shouldUpdate, don't overwrite it.
target.shouldUpdate = target.shouldUpdate || _shouldUpdate
return target
}
function _shouldUpdate( component, nextProps, nextState ) {
let {props, state} = component
// update on any state changes (as is the default)
if (state !== nextState) {
return true
}
// update if props are shallowly not equal, inspired by PureRenderMixin
let keys = Object.keys(props), key
if (keys.length !== Object.keys(nextProps).length) {
return true
}
for(var i = keys.length -1; i >= 0, key = keys[i]; i--) {
if (nextProps[key] !== props[key]) {
return true
}
}
return false
}
/** @jsx dom*/
import {dom, tree, render} from 'deku'
import mob from 'mobservable'
import observant from './observant'
let links = mob.fromJson([
{ name:'Google' },
{ name:'Github' }
])
function addLink() {
let name = prompt("Name:")
if( name ) {
links.push( mob.fromJson({ name }) )
}
}
const Link = observant({
render({ props }) {
return (
<li>{ props.link.name }</li>
)
}
})
const List = observant({
render({ props }) {
return (
<div>
<ul>
{ props.links.map( link => (
<Link link={ link }/>
))}
</ul>
<button onClick={ addLink }>
Add Link
</button>
</div>
)
}
})
let root = tree( <List links={ links }/> )
render( root, document.body )
@orrybaram
Copy link

orrybaram commented Jun 21, 2016

@mattmccray Hey! I wanted to pick your brain for a second. I've been trying to port this gist to use modx, and have been running into some issues getting it to work. If you have a sec, can you check out https://github.com/orrybaram/mobx-deku-boilerplate (the deku binding can be found here) and let me know if you have any ideas on how to pull it together? I essentially swapped out the mod.watch() function for modx.autorun() but it doesn't seem to work the same. ¯_(ツ)_/¯ Any help would be appreciated!

Update Nevermind, got it to work! Thanks for this starting point!

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