Last active
December 19, 2015 16:11
-
-
Save limdauto/42ecd18eaec4e9083882 to your computer and use it in GitHub Desktop.
VM/Controller in Mithril Discussion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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