Skip to content

Instantly share code, notes, and snippets.

@gilbert
Last active October 6, 2019 23:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilbert/973e16c170330908dcff to your computer and use it in GitHub Desktop.
Save gilbert/973e16c170330908dcff to your computer and use it in GitHub Desktop.
Mithril View-Model Example
var Comment = {]
Comment.create = function (attrs) {
return m.request({ method: 'POST', url: '/comments', data: attrs })
}
// A view-model is basically a temporary, disposable copy of a model.
// It allows the user can either commit or cancel the changes they make.
Comment.vm = function (attrs) {
attrs = attrs || {}
return {
id: attrs.id || null,
content: attrs.content || ''
}
}
var CommentEditor = {}
CommentEditor.controller = function (options) {
var ctrl = this
ctrl.commentVM = Comment.vm(options.comment)
}
CommentEditor.view = function (ctrl, options) {
var vm = ctrl.commentVM
return m('.comment-editor', [
m('textarea', { onchange: m.setValue(ctrl.commentVM, 'content') }, vm.content),
m('button', { onclick: options.onCancel }, 'Cancel'),
m('button', { onclick: options.onSave.bind(null, ctrl.commentVM) }, 'Save')
])
}
// Taken from https://gist.github.com/mindeavor/0bf02f1f21c72de9fb49
m.setValue = function (obj, prop) {
return m.withAttr('value', function(value) { obj[prop] = value })
}
//
// Creating new comments
//
var App = {}
App.view = function () {
return m('.app', [
m('h1', 'Create New Comment:'),
m.component(CommentEditor)
])
}
//
// Editing existing comments
//
var commentModels = [
{ id: 10, content: "Hello!" },
{ id: 11, content: "o hai" }
]
var App = {}
App.view = function (ctrl) {
return m('.app', [
commentModels.map(function(comment) {
return m.component(CommentView, { comment: comment })
})
])
}
var CommentView = {}
CommentView.controller = function () {
var ctrl = this
ctrl.isEditing = false
}
CommentView.view = function (ctrl, options) {
if (ctrl.isEditing) {
return m('.comment', [
m.component(CommentEditor, {
comment: options.comment,
onCancel: m.set(ctrl, 'isEditing', false)
})
])
}
else {
return m('.comment', [
m('p', options.comment.content),
m('button', { onclick: m.set(ctrl, 'isEditing', true) })
])
}
}
// Taken from https://gist.github.com/mindeavor/0bf02f1f21c72de9fb49
m.set = function (obj, prop, value) {
return function() { obj[prop] = value })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment