Skip to content

Instantly share code, notes, and snippets.

@viciouslabs
Last active October 15, 2017 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viciouslabs/03bb619f4dc1a640c0eb932362a5d5fe to your computer and use it in GitHub Desktop.
Save viciouslabs/03bb619f4dc1a640c0eb932362a5d5fe to your computer and use it in GitHub Desktop.
MobX for those who can't get over their ex, Redux
class Message {
@observable message = "Hello world"
// fictional example, if author is immutable, we just need to store a reference and shouldn't turn it into a mutable, observable object
@observable.ref author = null
}
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {observer} from "mobx-react";
@observer
class TodoListView extends Component {
render() {
return <div>
<ul>
{this.props.todoList.todos.map(todo =>
<TodoView todo={todo} key={todo.id} />
)}
</ul>
Tasks left: {this.props.todoList.unfinishedTodoCount}
</div>
}
}
const TodoView = observer(({todo}) =>
<li>
<input
type="checkbox"
checked={todo.finished}
onClick={() => todo.finished = !todo.finished}
/>{todo.title}
</li>
)
const store = new TodoList();
ReactDOM.render(<TodoListView todoList={store} />, document.getElementById('mount'));
import SomeOtherModel from './SomeOtherModel'
import TodoModel from './TodoModel'
const otherModel = new SomeOtherModel()
const todoModel = new TodoModel()
const storeRefs = {
  otherModel,
  todoModel,
}
export function dispatchAction({action, ...params}) {
  Object.keys(storeRefs).forEach(store => {
    conststoreRef=storeRefs[store]
    if (storeRef[action] && (typeofstoreRef[action]) ==='function' ) {
      storeRef[action].call(storeRef, ...params)
    }
  })
}
function Timer() {
extendObservable(this, {
start: Date.now(),
current: Date.now(),
get elapsedTime() {
return (this.current - this.start) + "milliseconds"
},
tick: action(function() {
this.current = Date.now()
}),
[ACTION_NAME]: action(function() {
this.someProperty = 'someValue'
})
})
}
class TodoList {
@observable todos = [];
@computed get unfinishedTodoCount() {
return this.todos.filter(todo =&amp;gt; !todo.finished).length;
}
}
store1.setTitle('new title');
store2.setTitle('new title');
store3.setTitle('new title');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment