Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created March 24, 2014 00:30
Show Gist options
  • Save Raynos/9732132 to your computer and use it in GitHub Desktop.
Save Raynos/9732132 to your computer and use it in GitHub Desktop.
var addEvent = require('dom-delegator/add-event');
var h = require('virtual-dom/h');
var main = require('vdom-main');
var Delegator = require('dom-delegator');
var hash = require('observ-hash');
var value = require('observ');
var EventSinks = require('event-sinks/geval');
module.exports = app;
function app() {
var input = Input()
var state = State(input.sinks)
// wire up events to updating logic
input.events.clicks(updateClicks.bind(null, state))
// loop will do diff/batch every time you call
// loop.update(newState)
var loop = main(state(), Render)
state(loop.update)
// return DOM element
return loop.target
}
function Input() {
var del = Delegator()
var events = EventSinks(del.id, ['clicks'])
return { events: events, sinks: events.sinks }
}
function State(sinks) {
return hash({
clicks: value(0),
sinks: sinks
})
}
function updateClicks(state) {
state.clicks.set(state.clicks() + 1)
}
function Render(state) {
return h('div', {
'data-click': event(state.sinks.clicks)
}, state.clicks)
}
// this is where I need the hook.
// the reason i need a hook is because dom-delegator needs
// access to a real DOM node to be able to add events
function event(sink, arg) {
return function (elem, property) {
var eventType = property.substr(5)
// for a given id (each delegator has a unique id)
// we say for this (elem, eventType) tuple add this
// listener function.
// This means that when the global 'click' event happens
// on the document.body and one of the targets is
// this elem we will invoke the supplied function
// with the DOM event
addEvent(sink.id, elem, eventType,
sink.write.bind(null, arg))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment