Skip to content

Instantly share code, notes, and snippets.

@willkessler
Created June 21, 2016 04:55
Show Gist options
  • Save willkessler/4a4f452d0dfff205e7cf2c75f2c745ef to your computer and use it in GitHub Desktop.
Save willkessler/4a4f452d0dfff205e7cf2c75f2c745ef to your computer and use it in GitHub Desktop.
const choo = require('choo')
const app = choo()
function view (params, state, send) {
let newView = choo.view`
<main>
<h1>${state.title}</h1>
<ul id="sortedList">
${state.theList.map(function (item) {
return choo.view`<li data-id="${item}">${item}</li>`
})}
</ul>
<form onsubmit=${onSubmit}>
New: <input type="text" name="new_item" value="foo"
autofocus
onkeydown=${e => e.keyCode === 13 && onEnter(event) || true}
>
<input type="submit" value="Submit">
</form>
</main>
`
return newView;
function onEnter (event) {
console.log('onEnter hit');
send('addItem', { data: event.target.value });
event.preventDefault();
}
function onSubmit(event) {
console.log('onsubmit hit');
send('addItem', { data: event.target.value });
event.preventDefault();
}
}
app.model({
state: {
title: 'Some title',
theList: ['item 1', 'item 2', 'item 3', 'item 4' ]
},
reducers: {
addItem: function(action,state) {
console.log('addItem: action=', action.data, ' state=', state);
return { title: action.data, theList: state.theList.concat(action.data) }
},
replaceItems: function(action,state) {
console.log('replaceItems: action=', action.data, ' state=', state);
return { theList: action.data }
},
}
});
console.log('sortable');
app.router((route) => [
route('/', view)
]);
const tree = app.start();
document.body.appendChild(tree);
Sortable.create(document.getElementById('sortedList'), {
draggable: 'li',
onEnd: function () {
console.log('on end');
},
onUpdate: function(e) {
console.log('on update');
let newItems = ['a','b','c'];
app.send('replaceItems', { data: newItems });
var oldPosition = e.item.getAttribute('data-id');
var newPosition = this.toArray().indexOf(oldPosition);
console.log("Moved " + oldPosition + " to " + newPosition);
// list.splice(newPosition, 0, list.splice(oldPosition, 1)[0]);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment