Skip to content

Instantly share code, notes, and snippets.

@mikeyb
Forked from paudirac/devices.js
Created June 29, 2017 04:02
Show Gist options
  • Save mikeyb/df46c79e46bd711aecfa1267fe498a0b to your computer and use it in GitHub Desktop.
Save mikeyb/df46c79e46bd711aecfa1267fe498a0b to your computer and use it in GitHub Desktop.
Mithril demonstration.
var m = require('mithril');
var devices = {};
devices.controller = function() {
let url = "http://localhost:8989/devices";
return {
devices: m.request({method: "GET", url: url }),
remove: function(name) {
return m.request({ method: "DELETE", url: `${url}/${name}` });
}
};
};
function table_header(schema) {
function th(item) {
return m('th', item.title || '');
}
return m('thead', [
m('tr', schema.map(th))
]);
}
function table_body(schema, items) {
function tr(item) {
return m('tr', schema.map(s => s.td(item)));
}
return m('tbody', items.map(tr));
}
function table(schema, items) {
return [
m('table.table.table-condensed.table-stripped', [
table_header(schema),
table_body(schema, items)
])
];
}
function prop(k) {
return function(obj) {
return obj[k];
};
}
function compose(a, b) {
return function(item) {
return b(a(item));
};
}
function td(n) { return m('td', n); }
devices.view = function(ctrl) {
function remove_button(item) {
let btn = m("a.btn.btn-danger.btn-xs", {
onclick: function() {
ctrl.remove(item.Name);
return false;
}
}, 'Remove');
return m('td', btn);
}
var schema = [
{ title: 'Name', td: compose(prop('Name'), td) },
{ title: 'Protocol', td: compose(compose(prop('Protocol'), prop('Name')), td) },
{ title: 'IP', td: compose(prop('IP'), td) },
{ title: 'Port', td: compose(prop('Port'), td) },
{ title: '', td: remove_button }
];
return table(schema, ctrl.devices());
};
module.exports = devices;
let m = require('mithril'),
u = require('../utils/utils.js');
var form = {};
form.controller = function() {
var values = {
Name: m.prop('name'),
Protocol: m.prop('protocol'),
IP: m.prop('ip'),
Port: m.prop('port')
};
return {
values: values,
save: function() {
console.log(`values: ${JSON.stringify(values)}`);
return m.request({
method: 'POST',
url: 'http://localhost:8989/devices',
data: values
});
},
cancel: function() {
values({
Name: 'name',
Protocol: 'protocol',
IP: 'ip',
Port: 'port'
});
}
};
};
function i(label, type, value) {
return m('div.form-group',
m('label', label),
m('input', {type: type, class: 'form-control', onchange: m.withAttr('value', value), value: value() })
);
}
form.view = function(ctrl) {
return [
m('form', [
i('Name', 'text', ctrl.values.Name),
i('Protocol', 'text', ctrl.values.Protocol),
i('IP', 'text', ctrl.values.IP),
i('Port', 'text', ctrl.values.Port),
m('button.btn.btn-primary', {type: 'button', onclick: ctrl.save }, 'Save'),
m('button.btn.btn-default', {onclick: ctrl.cancel}, 'Cancel')
])
];
};
module.exports = form;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment