DEV Community

artydev
artydev

Posted on

Mithril and Mobx

Porsager wrote a nice script on using Mobx within Mithril

const { decorate, observable, computed, autorun } = mobx;

class Todo {
  id = Math.random();
  title = '';
  finished = false;
  constructor(title) {
    this.title = title 
  }
}

decorate(Todo, {
  title: observable,
  finished: observable
})

class TodoList {
  todos = [];
  get unfinishedTodoCount() {
    return this.todos.filter(todo => !todo.finished).length;
  }
}

decorate(TodoList, {
  unfinishedTodoCount: computed
})

const store = new TodoList()

const todoListView = todo =>
  m('li',
    m('input', {
      type: 'checkbox',
      onchange: () => todo.finished = !todo.finished,
      checked: todo.finished
    }),
    todo.title
  )

const todoView = () => {
  let title = ''

  return { view: () => [
    m('form', {
      onsubmit: e => {
        e.preventDefault()
        store.todos.push(new Todo(title))
        title = ''
      }
    },
      m('input', {
        value: title,
        oninput: e => title = e.target.value
      }),
      m('button', 'add')
    ),
    m('ul',
      store.todos.map(todoListView)
    ),
    store.unfinishedTodoCount + ' unfinished todos'
  ]
  }
}

m.mount(document.body, todoView)
autorun(m.redraw)

You can test it here : Mithril & Mobx

Top comments (0)