Skip to content

Instantly share code, notes, and snippets.

@limdauto
Last active December 19, 2015 16: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 limdauto/42ecd18eaec4e9083882 to your computer and use it in GitHub Desktop.
Save limdauto/42ecd18eaec4e9083882 to your computer and use it in GitHub Desktop.
VM/Controller in Mithril Discussion
// some model holding data state
class TodoItem {
constructor() {
this.isAchieved = m.prop(false);
}
}
// vm holds application state -- http://lhorie.github.io/mithril-blog/what-is-a-view-model.html
class TodoVM extends SomeEventEmitter {
constructor() {
this.isClicked = m.prop(false);
}
}
// controller defines api communication, model instantiation, etc.
class BaseController {
constructor() {
this.todos = m.prop([]);
m.request({
url: '/api/todo-list/',
type: TodoItem
}).then(this.todos);
this.vm = new TodoVM();
}
}
// controller can differ between contexts
class PremiumController extends BaseController {
constructor() {
super();
this.vm.on('click', () => {
this.vm.isClicked(true);
alert('hey, you are premium');
});
}
}
class NormalController extends BaseController {
constructor() {
super();
this.vm.on('click', () => {
this.vm.isClicked(true);
alert('hey, you need to pay');
});
}
}
var todoComponent = {
// pure function view that renders base on data states and application states
view(ctrl) {
return m('.stuff', [
m('ul', ctrl.todos().filter(item => !item.isAchieved()).map(item => m('li', item)))
m('button', {onclick: () => vm.emit('click')}),
m('span', ctrl.vm.isClicked() ? 'button is clicked' : 'button is not clicked')
]);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment