Skip to content

Instantly share code, notes, and snippets.

View yelouafi's full-sized avatar

Yassine Elouafi yelouafi

View GitHub Profile
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) ))
]);
}
// module likeComp.js
function likeView(state, handler) { ... }
function likeHandler(state, e) { ... }
export default {view: likeView, handler: likeHandler};
function main(initState, element, {view, update}) {
const newVnode = view(initState, event => {
const newState = update(initState, event);
main(newState, newVnode, {view, update});
});
patch(oldVnode, newVnode);
}
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;
}
//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);
// 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}`),
function view(name) {
return h('div', [
h('input', {
props: { type: 'text', placeholder: 'Type your name' },
on : { input: update }
}),
h('hr'),
h('div', 'Hello ' + name)
]);
}
function view(currentDate) {
return h('div', 'Current date ' + currentDate);
}
var oldVnode = document.getElementById('placeholder');
setInterval( () => {
const newVnode = view(new Date());
oldVnode = patch(oldVnode, newVnode);
}, 1000);
import h from 'snabbdom/h';
var vnode = h('div', {style: {fontWeight: 'bold'}}, 'Hello world');
patch(document.getElementById('placeholder'), vnode);
import snabbdom from 'snabbdom';
const patch = snabbdom.init([ // Init patch function with choosen modules
require('snabbdom/modules/class'), // makes it easy to toggle classes
require('snabbdom/modules/props'), // for setting properties on DOM elements
require('snabbdom/modules/style'), // handles styling on elements with support for animations
require('snabbdom/modules/eventlisteners'), // attaches event listeners
]);