Mobx + React simple todolist
ES5 example
by Matt Ruby
HTML
<script src="https://npmcdn.com/[email protected]/lib/mobx.umd.js"></script>
<script src="https://npmcdn.com/[email protected]"></script>
<body>
<div id="mount">
</div>
</body>
JavaScript
var Todo = function (title) {
this.id= Math.random();
mobx.extendObservable(this,
{
title: title,
finished: false
}
);
}
var TodoList = function () {
mobx.extendObservable(this,
{
todos: [],
unfinishedTodoCount: function () {
return this.todos.filter(function (todo) {
return !todo.finished;
}).length;
}
});
}
var TodoListView = mobxReact.observer(
React.createClass({
render: function () {
var listItems = this.props.todoList.todos.map(function (todo) {
return React.createElement(TodoView, {todo: todo, key: todo.id});
});
return React.createElement('div', null,
React.createElement('ul', null, listItems),
'Tasks left: ' + this.props.todoList.unfinishedTodoCount
);
}
})
);
var TodoView = mobxReact.observer(
React.createClass({
render: function () {
var todo = this.props.todo;
return React.createElement('li', null,
React.createElement('input', {
type:"checkbox",
checked: todo.finished,
onClick: this.selectHandler
}),
todo.title
);
},
selectHandler: function() {
this.props.todo.finished = !this.props.todo.finished;
}
})
);
var store = new TodoList();
React.render(React.createElement(TodoListView, { todoList:store}), document.getElementById('mount'));
store.todos.push(
new Todo("Get Coffee"),
new Todo("Write simpler code")
);
store.todos[0].finished = true;