Skip to content

Instantly share code, notes, and snippets.

View yelouafi's full-sized avatar

Yassine Elouafi yelouafi

View GitHub Profile
// state : {likes: Number, dislikes: Number}
function likeView(state, handler) {
return h('div', [
h('button', {
on : { click: handler.bind(null, {action: 'like'}) }
}, 'Like'),
h('button', {
on : { click: handler.bind(null, {action: 'dislike'}) }
}, 'Dislike'),
h('div', `Likes : ${state.likes}`),
//view() inchanged
function handler(state, event) {
return { name: event.target.value };
}
function viewHandler(state, event) {
const newState = handler(state, event);
const newVnode = view(newState, viewHandler);
function likeHandler(state, e) {
if(e.action === 'like')
return {...state, likes: state.likes + 1};
else if(e.action === 'dislike')
return {...state, dislikes: state.dislikes + 1};
return state;
}
function main(initState, element, {view, update}) {
const newVnode = view(initState, event => {
const newState = update(initState, event);
main(newState, newVnode, {view, update});
});
patch(oldVnode, newVnode);
}
// module likeComp.js
function likeView(state, handler) { ... }
function likeHandler(state, e) { ... }
export default {view: likeView, handler: likeHandler};
function likeListView(state, handler) {
return h('div', [
h('button', {
on: { click: handler.bind(null, {action: 'add'}) }
}, 'Add'),
h('ul.unstyled', state.items.map( item => likeItemView(item, handler) ))
]);
}
// item : {id, like}
function likeItemView(item, handler) {
return h('li', { key: item.id }, [
likeComp.view(item.like, e => handler({ action: 'likeAction', id: item.id, data: e}))
]);
}
const INC = Symbol('inc');
const DEC = Symbol('dec');
// model : Number
function view(count, handler) {
return h('div', [
h('button', {
on : { click: handler.bind(null, {type: INC}) }
}, '+'),
h('button', {
import test from 'tape';
import { update, actions } from '../app/js/counter';
test('counter update function', (assert) => {
var count = 10;
count = update(count, {type: actions.INC});
assert.equal(count, 11);
count = update(count, {type: actions.DEC});
...
const INIT = Symbol('init');
function update(count, action) {
return ...
: action.type === INIT ? action.data
...
}