Skip to content

Instantly share code, notes, and snippets.

@jfsiii
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jfsiii/9d67402b842e14bd22b0 to your computer and use it in GitHub Desktop.
Save jfsiii/9d67402b842e14bd22b0 to your computer and use it in GitHub Desktop.
requirebin sketch
// returns {}, so it throws "TypeError: undefined is not a function" on document.body.appendChild
// var document = require("global/document")
var document = require("global").document;
var Delegator = require("html-delegator")
var h = require("hyperscript")
var addEvent = require("html-delegator/add-event")
var EventSinks = require("event-sinks")
var delegator = Delegator(document.body)
// changed these lines to prevent errors
var inputs = EventSinks(delegator.id, ["textClicked"]);
var emitter = inputs.emitter
var sinks = inputs.sinks
//
var elem = h("div.foo", [
h("div.bar", "bar"),
h("span.baz", "baz")
])
var bar = elem.querySelector(".bar")
var baz = elem.querySelector(".baz")
document.body.appendChild(elem)
// add individual elems.
addEvent(bar, "click", sinks.textClicked, {
type: "bar"
})
addEvent(baz, "click", sinks.textClicked, {
type: "baz"
})
emitter.on("textClicked", function (tuple) {
var value = tuple.value
console.log("doSomething", value.type)
})
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({global:[function(require,module,exports){(function(global){if(typeof window!=="undefined"){module.exports=window}else if(typeof global!=="undefined"){module.exports=global}else{module.exports={}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){},{}],2:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){if(encoding==="base64")subject=base64clean(subject);length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new Error("First argument needs to be a number, array or string.");var buf;if(TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}return buf}Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.byteLength=function(str,encoding){var ret;str=str.toString();switch(encoding||"utf8"){case"hex":ret=str.length/2;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"ascii":case"binary":case"raw":ret=str.length;break;case"base64":ret=base64ToBytes(str).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;default:throw new Error("Unknown encoding")}return ret};Buffer.concat=function(list,totalLength){assert(isArray(list),"Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.compare=function(a,b){assert(Buffer.isBuffer(a)&&Buffer.isBuffer(b),"Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y){return-1}if(y<x){return 1}return 0};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;assert(strLen%2===0,"Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);assert(!isNaN(byte),"Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string),buf,offset,length);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new Error("Unknown encoding")}return ret};Buffer.prototype.toString=function(encoding,start,end){var self=this;encoding=String(encoding||"utf8").toLowerCase();start=Number(start)||0;end=end===undefined?self.length:Number(end);if(end===start)return"";var ret;switch(encoding){case"hex":ret=hexSlice(self,start,end);break;case"utf8":case"utf-8":ret=utf8Slice(self,start,end);break;case"ascii":ret=asciiSlice(self,start,end);break;case"binary":ret=binarySlice(self,start,end);break;case"base64":ret=base64Slice(self,start,end);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leSlice(self,start,end);break;default:throw new Error("Unknown encoding")}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};Buffer.prototype.equals=function(b){assert(Buffer.isBuffer(b),"Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.compare=function(b){assert(Buffer.isBuffer(b),"Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(!target_start)target_start=0;if(end===start)return;if(target.length===0||source.length===0)return;assert(end>=start,"sourceEnd < sourceStart");assert(target_start>=0&&target_start<target.length,"targetStart out of bounds");assert(start>=0&&start<source.length,"sourceStart out of bounds");assert(end>=0&&end<=source.length,"sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<100||!TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function binarySlice(buf,start,end){return asciiSlice(buf,start,end)}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;if(TYPED_ARRAY_SUPPORT){return Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;var newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}return newBuf}};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert){assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to read beyond buffer length")}if(offset>=this.length)return;return this[offset]};function readUInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val;if(littleEndian){val=buf[offset];if(offset+1<len)val|=buf[offset+1]<<8}else{val=buf[offset]<<8;if(offset+1<len)val|=buf[offset+1]}return val}Buffer.prototype.readUInt16LE=function(offset,noAssert){return readUInt16(this,offset,true,noAssert)};Buffer.prototype.readUInt16BE=function(offset,noAssert){return readUInt16(this,offset,false,noAssert)};function readUInt32(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val;if(littleEndian){if(offset+2<len)val=buf[offset+2]<<16;if(offset+1<len)val|=buf[offset+1]<<8;val|=buf[offset];if(offset+3<len)val=val+(buf[offset+3]<<24>>>0)}else{if(offset+1<len)val=buf[offset+1]<<16;if(offset+2<len)val|=buf[offset+2]<<8;if(offset+3<len)val|=buf[offset+3];val=val+(buf[offset]<<24>>>0)}return val}Buffer.prototype.readUInt32LE=function(offset,noAssert){return readUInt32(this,offset,true,noAssert)};Buffer.prototype.readUInt32BE=function(offset,noAssert){return readUInt32(this,offset,false,noAssert)};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert){assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to read beyond buffer length")}if(offset>=this.length)return;var neg=this[offset]&128;if(neg)return(255-this[offset]+1)*-1;else return this[offset]};function readInt16(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val=readUInt16(buf,offset,littleEndian,true);var neg=val&32768;if(neg)return(65535-val+1)*-1;else return val}Buffer.prototype.readInt16LE=function(offset,noAssert){return readInt16(this,offset,true,noAssert)};Buffer.prototype.readInt16BE=function(offset,noAssert){return readInt16(this,offset,false,noAssert)};function readInt32(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to read beyond buffer length")}var len=buf.length;if(offset>=len)return;var val=readUInt32(buf,offset,littleEndian,true);var neg=val&2147483648;if(neg)return(4294967295-val+1)*-1;else return val}Buffer.prototype.readInt32LE=function(offset,noAssert){return readInt32(this,offset,true,noAssert)};Buffer.prototype.readInt32BE=function(offset,noAssert){return readInt32(this,offset,false,noAssert)};function readFloat(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset+3<buf.length,"Trying to read beyond buffer length")}return ieee754.read(buf,offset,littleEndian,23,4)}Buffer.prototype.readFloatLE=function(offset,noAssert){return readFloat(this,offset,true,noAssert)};Buffer.prototype.readFloatBE=function(offset,noAssert){return readFloat(this,offset,false,noAssert)};function readDouble(buf,offset,littleEndian,noAssert){if(!noAssert){assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset+7<buf.length,"Trying to read beyond buffer length")}return ieee754.read(buf,offset,littleEndian,52,8)}Buffer.prototype.readDoubleLE=function(offset,noAssert){return readDouble(this,offset,true,noAssert)};Buffer.prototype.readDoubleBE=function(offset,noAssert){return readDouble(this,offset,false,noAssert)};Buffer.prototype.writeUInt8=function(value,offset,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"trying to write beyond buffer length");verifuint(value,255)}if(offset>=this.length)return;this[offset]=value;return offset+1};function writeUInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"trying to write beyond buffer length");verifuint(value,65535)}var len=buf.length;if(offset>=len)return;for(var i=0,j=Math.min(len-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}return offset+2}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return writeUInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return writeUInt16(this,value,offset,false,noAssert)};function writeUInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"trying to write beyond buffer length");verifuint(value,4294967295)}var len=buf.length;if(offset>=len)return;for(var i=0,j=Math.min(len-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}return offset+4}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return writeUInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return writeUInt32(this,value,offset,false,noAssert)};Buffer.prototype.writeInt8=function(value,offset,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset<this.length,"Trying to write beyond buffer length");verifsint(value,127,-128)}if(offset>=this.length)return;if(value>=0)this.writeUInt8(value,offset,noAssert);else this.writeUInt8(255+value+1,offset,noAssert);return offset+1};function writeInt16(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+1<buf.length,"Trying to write beyond buffer length");verifsint(value,32767,-32768)}var len=buf.length;if(offset>=len)return;if(value>=0)writeUInt16(buf,value,offset,littleEndian,noAssert);else writeUInt16(buf,65535+value+1,offset,littleEndian,noAssert);return offset+2}Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return writeInt16(this,value,offset,true,noAssert)};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return writeInt16(this,value,offset,false,noAssert)};function writeInt32(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to write beyond buffer length");verifsint(value,2147483647,-2147483648)}var len=buf.length;if(offset>=len)return;if(value>=0)writeUInt32(buf,value,offset,littleEndian,noAssert);else writeUInt32(buf,4294967295+value+1,offset,littleEndian,noAssert);return offset+4}Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return writeInt32(this,value,offset,true,noAssert)};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return writeInt32(this,value,offset,false,noAssert)};function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+3<buf.length,"Trying to write beyond buffer length");verifIEEE754(value,3.4028234663852886e38,-3.4028234663852886e38)}var len=buf.length;if(offset>=len)return;ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){assert(value!==undefined&&value!==null,"missing value");assert(typeof littleEndian==="boolean","missing or invalid endian");assert(offset!==undefined&&offset!==null,"missing offset");assert(offset+7<buf.length,"Trying to write beyond buffer length");verifIEEE754(value,1.7976931348623157e308,-1.7976931348623157e308)}var len=buf.length;if(offset>=len)return;ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;assert(end>=start,"end < start");if(end===start)return;if(this.length===0)return;assert(start>=0&&start<this.length,"start out of bounds");assert(end>=0&&end<=this.length,"end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.inspect=function(){var out=[];var len=this.length;for(var i=0;i<len;i++){out[i]=toHex(this[i]);if(i===exports.INSPECT_MAX_BYTES){out[i+1]="...";break}}return"<Buffer "+out.join(" ")+">"};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new Error("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArray(subject){return(Array.isArray||function(subject){return Object.prototype.toString.call(subject)==="[object Array]"})(subject)}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){var b=str.charCodeAt(i);if(b<=127){byteArray.push(b)}else{var start=i;if(b>=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j<h.length;j++){byteArray.push(parseInt(h[j],16))}}}return byteArray}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}function verifuint(value,max){assert(typeof value==="number","cannot write a non-number as a number");assert(value>=0,"specified a negative value for writing an unsigned value");assert(value<=max,"value is larger than maximum value for type");assert(Math.floor(value)===value,"value has a fractional component")}function verifsint(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value");assert(Math.floor(value)===value,"value has a fractional component")}function verifIEEE754(value,max,min){assert(typeof value==="number","cannot write a non-number as a number");assert(value<=max,"value larger than maximum allowed value");assert(value>=min,"value smaller than minimum allowed value")}function assert(test,message){if(!test)throw new Error(message||"Failed assertion")}},{"base64-js":3,ieee754:4}],3:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],4:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],5:[function(require,module,exports){var DELIMINATOR=":";module.exports=DELIMINATOR},{}],6:[function(require,module,exports){var ID_SEPERATOR="@";module.exports=ID_SEPERATOR},{}],7:[function(require,module,exports){var SINK_MAP={};module.exports=SINK_MAP},{}],8:[function(require,module,exports){var getField=require("dom-delegator/symbol/get-field");var DELIMINATOR=require("./constants/deliminator.js");var ID_SEPERATOR=require("./constants/id-seperator.js");var SINK_MAP=require("./constants/sink-map.js");module.exports=getListener;function getListener(surface,id,target,type){if(target===null){return null}var events=getField(target,id);var tuple=events&&events[type];if(!tuple){var value=surface.fetchAttr(target,type);tuple=unpackAttrValue(id,value)}if(!tuple){return getListener(surface,id,surface.getParent(target),type)}return{currentTarget:target,data:tuple[0],sink:tuple[1]}}function unpackAttrValue(delId,value){if(!value){return null}var parts=value.split(DELIMINATOR);var head=parts[0];var headParts=head.split(ID_SEPERATOR);var key=headParts[0];var id=headParts[1];if(delId!==id){return null}var sinks=SINK_MAP[id];if(!sinks){return null}var sink=sinks[key];if(!sink){return null}var rest=parts.slice(1).join(DELIMINATOR);var data=parseOrUndefined(rest);return[data,sink]}function parseOrUndefined(data){var json;try{json=JSON.parse(data)}catch(err){json=undefined}return json}},{"./constants/deliminator.js":5,"./constants/id-seperator.js":6,"./constants/sink-map.js":7,"dom-delegator/symbol/get-field":22}],9:[function(require,module,exports){var DOMSurface=require("dom-delegator/dom-surface");var DataSet=require("data-set");var getListener=require("./get-listener.js");var HTMLSurface={is:DOMSurface.is,defaultTarget:DOMSurface.defaultTarget,allEvents:DOMSurface.allEvents,addListener:DOMSurface.addListener,getParent:DOMSurface.getParent,getListener:getListener,fetchAttr:fetchAttr};module.exports=HTMLSurface;function fetchAttr(target,type){return DataSet(target)[type]}},{"./get-listener.js":8,"data-set":10,"dom-delegator/dom-surface":15}],10:[function(require,module,exports){var Weakmap=require("weakmap");var Individual=require("individual");var datasetMap=Individual("__DATA_SET_WEAKMAP",Weakmap());module.exports=DataSet;function DataSet(elem){if(elem.dataset){return elem.dataset}var hash=datasetMap.get(elem);if(!hash){hash=createHash(elem);datasetMap.set(elem,hash)}return hash}function createHash(elem){var attributes=elem.attributes;var hash={};if(attributes===null||attributes===undefined){return hash}for(var i=0;i<attributes.length;i++){var attr=attributes[i];if(attr.name.substr(0,5)!=="data-"){continue}hash[attr.name.substr(5)]=attr.value}return hash}},{individual:11,weakmap:13}],11:[function(require,module,exports){var root=require("global");module.exports=Individual;function Individual(key,value){if(root[key]){return root[key]}Object.defineProperty(root,key,{value:value,configurable:true});return value}},{global:12}],12:[function(require,module,exports){(function(global){if(typeof global!=="undefined"){module.exports=global}else if(typeof window!=="undefined"){module.exports=window}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],13:[function(require,module,exports){void function(global,undefined_,undefined){var getProps=Object.getOwnPropertyNames,defProp=Object.defineProperty,toSource=Function.prototype.toString,create=Object.create,hasOwn=Object.prototype.hasOwnProperty,funcName=/^\n?function\s?(\w*)?_?\(/;function define(object,key,value){if(typeof key==="function"){value=key;key=nameOf(value).replace(/_$/,"")}return defProp(object,key,{configurable:true,writable:true,value:value})}function nameOf(func){return typeof func!=="function"?"":"name"in func?func.name:toSource.call(func).match(funcName)[1]}var Data=function(){var dataDesc={value:{writable:true,value:undefined}},datalock="return function(k){if(k===s)return l}",uids=create(null),createUID=function(){var key=Math.random().toString(36).slice(2);return key in uids?createUID():uids[key]=key},globalID=createUID(),storage=function(obj){if(hasOwn.call(obj,globalID))return obj[globalID];if(!Object.isExtensible(obj))throw new TypeError("Object must be extensible");var store=create(null);defProp(obj,globalID,{value:store});return store};define(Object,function getOwnPropertyNames(obj){var props=getProps(obj);if(hasOwn.call(obj,globalID))props.splice(props.indexOf(globalID),1);return props});function Data(){var puid=createUID(),secret={};
this.unlock=function(obj){var store=storage(obj);if(hasOwn.call(store,puid))return store[puid](secret);var data=create(null,dataDesc);defProp(store,puid,{value:new Function("s","l",datalock)(secret,data)});return data}}define(Data.prototype,function get(o){return this.unlock(o).value});define(Data.prototype,function set(o,v){this.unlock(o).value=v});return Data}();var WM=function(data){var validate=function(key){if(key==null||typeof key!=="object"&&typeof key!=="function")throw new TypeError("Invalid WeakMap key")};var wrap=function(collection,value){var store=data.unlock(collection);if(store.value)throw new TypeError("Object is already a WeakMap");store.value=value};var unwrap=function(collection){var storage=data.unlock(collection).value;if(!storage)throw new TypeError("WeakMap is not generic");return storage};var initialize=function(weakmap,iterable){if(iterable!==null&&typeof iterable==="object"&&typeof iterable.forEach==="function"){iterable.forEach(function(item,i){if(item instanceof Array&&item.length===2)set.call(weakmap,iterable[i][0],iterable[i][1])})}};function WeakMap(iterable){if(this===global||this==null||this===WeakMap.prototype)return new WeakMap(iterable);wrap(this,new Data);initialize(this,iterable)}function get(key){validate(key);var value=unwrap(this).get(key);return value===undefined_?undefined:value}function set(key,value){validate(key);unwrap(this).set(key,value===undefined?undefined_:value)}function has(key){validate(key);return unwrap(this).get(key)!==undefined}function delete_(key){validate(key);var data=unwrap(this),had=data.get(key)!==undefined;data.set(key,undefined);return had}function toString(){unwrap(this);return"[object WeakMap]"}try{var src=("return "+delete_).replace("e_","\\u0065"),del=new Function("unwrap","validate",src)(unwrap,validate)}catch(e){var del=delete_}var src=(""+Object).split("Object");var stringifier=function toString(){return src[0]+nameOf(this)+src[1]};define(stringifier,stringifier);var prep={__proto__:[]}instanceof Array?function(f){f.__proto__=stringifier}:function(f){define(f,stringifier)};prep(WeakMap);[toString,get,set,has,del].forEach(function(method){define(WeakMap.prototype,method);prep(method)});return WeakMap}(new Data);var defaultCreator=Object.create?function(){return Object.create(null)}:function(){return{}};function createStorage(creator){var weakmap=new WM;creator||(creator=defaultCreator);function storage(object,value){if(value||arguments.length===2){weakmap.set(object,value)}else{value=weakmap.get(object);if(value===undefined){value=creator(object);weakmap.set(object,value)}}return value}return storage}if(typeof module!=="undefined"){module.exports=WM}else if(typeof exports!=="undefined"){exports.WeakMap=WM}else if(!("WeakMap"in global)){global.WeakMap=WM}WM.createStorage=createStorage;if(global.WeakMap)global.WeakMap.createStorage=createStorage}((0,eval)("this"))},{}],14:[function(require,module,exports){var uuid=require("uuid");var listen=require("./listen.js");module.exports=createDelegator;function createDelegator(surface){return Delegator;function Delegator(target,opts){if(!surface.is(target)){opts=target;target=null}target=target||surface.defaultTarget;opts=opts||{};var delegator={id:opts.id||uuid(),target:target,listenTo:listenTo};if(opts.defaultEvents!==false){surface.allEvents.forEach(function(eventName){listen(surface,delegator,eventName)})}return delegator;function listenTo(eventName){listen(surface,delegator,eventName)}}}},{"./listen.js":17,uuid:20}],15:[function(require,module,exports){var document=require("global/document");var getListener=require("./get-listener.js");var allEvents=["blur","focus","focusin","focusout","load","resize","scroll","unload","click","dblclick","mousedown","mouseup","change","select","submit","keydown","keypress","keyup","error","contextmenu"];module.exports={is:isSurface,defaultTarget:document,allEvents:allEvents,addListener:addListener,getParent:getParent,getListener:getListener};function addListener(target,eventName,listener){target.addEventListener(eventName,listener,true)}function isSurface(target){return target&&typeof target.nodeName==="string"}function getParent(target){return target.parentNode}},{"./get-listener.js":16,"global/document":18}],16:[function(require,module,exports){var getField=require("./symbol/get-field.js");module.exports=getListener;function getListener(surface,id,target,type){if(target===null){return null}var events=getField(target,id);var tuple=events&&events[type];if(!tuple){return getListener(surface,id,surface.getParent(target),type)}return{currentTarget:target,data:tuple[0],sink:tuple[1]}}},{"./symbol/get-field.js":22}],17:[function(require,module,exports){module.exports=listen;function listen(surface,delegator,eventName){var target=delegator.target;var id=delegator.id;var getListener=surface.getListener;surface.addListener(target,eventName,function(ev){var listener=getListener(surface,id,ev.target,eventName);if(!listener){return}listener.sink.dispatch(listener,ev)})}},{}],18:[function(require,module,exports){if(typeof document!=="undefined"){module.exports=document}else{module.exports=require("min-document")}},{"min-document":1}],19:[function(require,module,exports){(function(global){var rng;if(global.crypto&&crypto.getRandomValues){var _rnds8=new Uint8Array(16);rng=function whatwgRNG(){crypto.getRandomValues(_rnds8);return _rnds8}}if(!rng){var _rnds=new Array(16);rng=function(){for(var i=0,r;i<16;i++){if((i&3)===0)r=Math.random()*4294967296;_rnds[i]=r>>>((i&3)<<3)&255}return _rnds}}module.exports=rng}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],20:[function(require,module,exports){(function(Buffer){var _rng=require("./rng");var BufferClass=typeof Buffer=="function"?Buffer:Array;var _byteToHex=[];var _hexToByte={};for(var i=0;i<256;i++){_byteToHex[i]=(i+256).toString(16).substr(1);_hexToByte[_byteToHex[i]]=i}function parse(s,buf,offset){var i=buf&&offset||0,ii=0;buf=buf||[];s.toLowerCase().replace(/[0-9a-f]{2}/g,function(oct){if(ii<16){buf[i+ii++]=_hexToByte[oct]}});while(ii<16){buf[i+ii++]=0}return buf}function unparse(buf,offset){var i=offset||0,bth=_byteToHex;return bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+"-"+bth[buf[i++]]+bth[buf[i++]]+"-"+bth[buf[i++]]+bth[buf[i++]]+"-"+bth[buf[i++]]+bth[buf[i++]]+"-"+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]+bth[buf[i++]]}var _seedBytes=_rng();var _nodeId=[_seedBytes[0]|1,_seedBytes[1],_seedBytes[2],_seedBytes[3],_seedBytes[4],_seedBytes[5]];var _clockseq=(_seedBytes[6]<<8|_seedBytes[7])&16383;var _lastMSecs=0,_lastNSecs=0;function v1(options,buf,offset){var i=buf&&offset||0;var b=buf||[];options=options||{};var clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;var msecs=options.msecs!==undefined?options.msecs:(new Date).getTime();var nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;var dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/1e4;if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&16383}if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0}if(nsecs>=1e4){throw new Error("uuid.v1(): Can't create more than 10M uuids/sec")}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;msecs+=122192928e5;var tl=((msecs&268435455)*1e4+nsecs)%4294967296;b[i++]=tl>>>24&255;b[i++]=tl>>>16&255;b[i++]=tl>>>8&255;b[i++]=tl&255;var tmh=msecs/4294967296*1e4&268435455;b[i++]=tmh>>>8&255;b[i++]=tmh&255;b[i++]=tmh>>>24&15|16;b[i++]=tmh>>>16&255;b[i++]=clockseq>>>8|128;b[i++]=clockseq&255;var node=options.node||_nodeId;for(var n=0;n<6;n++){b[i+n]=node[n]}return buf?buf:unparse(b)}function v4(options,buf,offset){var i=buf&&offset||0;if(typeof options=="string"){buf=options=="binary"?new BufferClass(16):null;options=null}options=options||{};var rnds=options.random||(options.rng||_rng)();rnds[6]=rnds[6]&15|64;rnds[8]=rnds[8]&63|128;if(buf){for(var ii=0;ii<16;ii++){buf[i+ii]=rnds[ii]}}return buf||unparse(rnds)}var uuid=v4;uuid.v1=v1;uuid.v4=v4;uuid.parse=parse;uuid.unparse=unparse;uuid.BufferClass=BufferClass;module.exports=uuid}).call(this,require("buffer").Buffer)},{"./rng":19,buffer:2}],21:[function(require,module,exports){module.exports={name:"dom-delegator",version:"3.2.2",description:"Decorate elements with delegated events",keywords:[],author:{name:"Raynos",email:"raynos2@gmail.com"},repository:{type:"git",url:"git://github.com/Raynos/dom-delegator.git"},main:"index",homepage:"https://github.com/Raynos/dom-delegator",contributors:[{name:"Raynos"}],bugs:{url:"https://github.com/Raynos/dom-delegator/issues",email:"raynos2@gmail.com"},dependencies:{global:"~2.0.7",uuid:"~1.4.1"},devDependencies:{tape:"~2.4.2",hyperscript:"~1.4.0","synthetic-dom-events":"~0.1.1",testling:"~1.6.0","event-sinks":"~1.0.1"},licenses:[{type:"MIT",url:"http://github.com/Raynos/dom-delegator/raw/master/LICENSE"}],scripts:{test:"node ./test/index.js",start:"node ./index.js",watch:"nodemon -w ./index.js index.js","travis-test":"istanbul cover ./test/index.js && ((cat coverage/lcov.info | coveralls) || exit 0)",cover:"istanbul cover --report none --print detail ./test/index.js","view-cover":"istanbul report html && google-chrome ./coverage/index.html","test-browser":"testem-browser ./test/browser/index.js",testem:"testem-both -b=./test/browser/index.js"},testling:{files:"test/index.js",browsers:["ie/8..latest","firefox/16..latest","firefox/nightly","chrome/22..latest","chrome/canary","opera/12..latest","opera/next","safari/5.1..latest","ipad/6.0..latest","iphone/6.0..latest","android-browser/4.2..latest"]},readme:'# dom-delegator\n\n<!--\n [![build status][1]][2]\n [![NPM version][3]][4]\n [![Coverage Status][5]][6]\n [![gemnasium Dependency Status][7]][8]\n [![Davis Dependency status][9]][10]\n-->\n\n<!-- [![browser support][11]][12] -->\n\nDecorate elements with delegated events\n\n## Motivation\n\nWhen building a web application you don\'t want to deal with\n messing around with the DOM directly if you can avoid it.\n\nWhat you really want to do is write application logic. Generally\n how application logic works is that you react to some kind of\n user input, run some logic and maybe change some state.\n\nLet\'s take a look at a calendar example. For a calendar we just\n want to react to a bunch of date change events and update the\n state of the calendar accordingly. We don\'t really care what\n triggers the date change events.\n\n```js\nvar Calendar = function () {\n var calendarState = { ... }\n var calendarInputs = { ... }\n\n calendarInputs.dateChange(function (newDate) {\n var d = new Date(newDate)\n\n calendarState.theTime.set(d)\n })\n}\n```\n\nThe above code is basically the application logic you want to\n express. Now imagine we had some kind of data binding that\n re-rendered the template / view for the calendar each time\n we update the calendarState.\n\n```js\nfunction render(calendarState) {\n var WEEK = 1000 * 60 * 60 * 24 * 7\n var prevWeek = +calendarState.theTime - WEEK\n var nextWeek = +calendarState.theTime + WEEK\n\n return h("div", [\n h("table", calendarGrid(calendarState)),\n h("div.controls", [\n h("button.prev", {\n "data-click": "dateChange:" + prevWeek\n }, "previous week"),\n h("button.next", {\n "data-click": "dateChange:" + nextWeek\n }, "next week")\n ])\n ])\n}\n```\n\nSomething will need to trigger the date change events, since we\n don\'t want to write any manual DOM code and since we already\n have a reactive templating system we should just add hooks to\n our templates that say when this DOM event occurs I want you\n to trigger this "meaningful" event in my system\n\n### Other motivations\n\n - solution should be a module, not a framework\n - solution should work recursively without namespace conflicts\n - solution should use event delegation, it shouldnt require\n binding to each DOM element manually\n - solution should allow rendering logic to be seperate from\n input handling logic.\n - solution doesn\'t require passing concrete functions to the\n rendering logic. The rendering and input handling most\n be loosely coupled.\n - solution should allow passing data to the event listener.\n - solution should discourage passing a DOM Event object to\n listener. You shouldn\'t read the `ev` or `ev.target` in\n your input handling code\n - library should only do input handling. Not input handling AND\n reactive rendering.\n\n## Example DOM\n\n```js\nvar document = require("global/document")\nvar Delegator = require("dom-delegator")\nvar h = require("hyperscript")\nvar addEvent = require("dom-delegator/add-event")\nvar EventSinks = require("event-sinks/geval")\n\nvar delegator = Delegator(document.body)\nvar events = EventSinks(delegator.id, ["textClicked"])\nvar sinks = events.sinks\nvar elem = h("div.foo", [\n h("div.bar", "bar"),\n h("span.baz", "baz")\n])\nvar bar = elem.querySelector(".bar")\nvar baz = elem.querySelector(".baz")\ndocument.body.appendChild(elem)\n\n\n// add individual elems.\naddEvent(bar, "click", sinks.textClicked, {\n type: "bar"\n})\naddEvent(baz, "click", sinks.textClicked, {\n type: "baz"\n})\n\nevents.textClicked(function (tuple) {\n var value = tuple.value\n\n console.log("doSomething", value.type)\n})\n```\n\n## Example data- attributes (Not working yet)\n\n```js\nvar document = require("global/document")\nvar Delegator = require("dom-delegator")\nvar h = require("hyperscript")\nvar event = require("dom-delegator/event")\nvar EventSinks = require("event-sinks/geval")\n\nvar delegator = Delegator(document.body)\nvar events = EventSinks(delegator.id, ["textClicked"])\nvar sinks = events.sinks\n\nvar elem = h("div.foo", [\n h("div.bar", { \n "data-click": event(sinks.textClicked, { type: "bar" })\n }, "bar"),\n h("div.baz", {\n "data-click": event(sinks.textClicked, { type: "baz" })\n }, "baz")\n])\ndocument.body.appendChild(elem)\n\ndelegator.textClicked(function (tuple) {\n var value = tuple.value\n\n console.log("doSomething", value.type)\n})\n```\n\n## Concept. (Not working)\n\nThe concept behind `dom-delegator` is to seperate declaring\n which UI elements trigger well named user input events from \n the event handling.\n\nFor example you might have an `input.js` where you handle user\n input, based on well named, non-DOM specific events.\n\n```js\n// input.js\nmodule.exports = Input\n\nfunction Input(state, sources) {\n // when the input event todo addition occurs\n // create a fresh item and add it\n sources.todoAdded(function (data, ev) {\n var value = ev.currentValue\n var todo = { title: value, completed: false }\n state.todos.push(todo)\n })\n\n // when the input event todo removal occurs\n // find the item and delete it from the list\n sources.todoRemoved(function (data, ev) {\n var id = data\n var index = -1\n state.todos.some(function (todo, itemIndex) {\n if (todo.id() === id) {\n index = itemIndex\n return true\n }\n })\n\n state.todos.splice(index, 1)\n })\n}\n```\n\nOne thing to notice here is that the input handling is coupled\n to keypress or click events. Those are implementation details\n of the declarative UI. The input handling has been described \n in a loosely coupled way.\n\nThe only coupling is that addition is based on the current value\n of the UI element that triggered the `todoAdded` event.\n\nSince we have defined our input handling, we now need to add\n the declarative event hooks to our UI.\n\nWe will use `HTML` and the `data- attributes` style interface\n for the delegator\n\n```html\n// ui.html\n<ul>\n <li data-id="4">\n <span class="todo-title">Some todo</span>\n <button data-click="todoRemoved:4">Remove</button>\n </li>\n</ul>\n<input class="add-todo" name="title" data-submit="todoAdded" />\n```\n\nHere we have decorated the todo item UI with a click event.\n whenever it is clicked it will emit the `todoRemoved` event\n and data will be set to the value after the `:` in this case\n `4`.\n\nWe also decorated the input with the `todoAdded` event.\n\nThe contract between the input handler and the UI is fairly\n loosely defined and it should be possible to refactor the UI\n without breaking the input handler. You can make the\n `todoAdded` event more generic like:\n\n```html\n// ui.html\n\n<div class="todo-addition" data-submit="todoAdded">\n <input class="add-todo" name="title" />\n</div>\n```\n\nThen update the input handler\n\n```js\n// when the input event todo addition occurs\n// create a fresh item and add it\ndelegator.sources.todoAdded(function (tuple) {\n var ev = tuple.ev\n var title = ev.currentValue.title\n var todo = { title: title, completed: false }\n state.todos.push(todo)\n})\n```\n\nWe have now bound the `todoAdded` event less tightly to \n `currentValue` and as long as there is some kind of `input`\n or `textarea` or `custom element` with a name called `\'title\'`\n the input handling code will still work.\n\n## Custom events (Not implemented)\n\nThe `type: "submit"` or `data-submit` event and the\n `type: "change"` or `data-change` event are not the normal\n DOM events for `addEventListener(\'submit\')` or \n `addEventListener(\'change\')` \n\n`data-submit` and `data-change` actually have more complex\n semantics. They can be bound to a container and well then\n emit the named event every time any child changes by the\n submit or change semantics.\n\nIf bound to a container it will use `FormData(...)` to read\n the currentValue as a hash of name to value of elements.\n\nIf bound to a single element it will get the value of that \n element based on what kind of element it is.\n\n### submit semantics\n\n`submit` triggers on `keypress` if the key is ENTER or triggers\n on a click if the click target is a `button` or `input` of \n type `"submit"`\n\n### change semantics\n\n`change` triggers on `change` (DOM change event) or on `keypress`\n\n## Installation\n\n`npm install dom-delegator`\n\n## Contributors\n\n - Raynos\n\n## MIT Licenced\n\n [1]: https://secure.travis-ci.org/Raynos/dom-delegator.png\n [2]: https://travis-ci.org/Raynos/dom-delegator\n [3]: https://badge.fury.io/js/dom-delegator.png\n [4]: https://badge.fury.io/js/dom-delegator\n [5]: https://coveralls.io/repos/Raynos/dom-delegator/badge.png\n [6]: https://coveralls.io/r/Raynos/dom-delegator\n [7]: https://gemnasium.com/Raynos/dom-delegator.png\n [8]: https://gemnasium.com/Raynos/dom-delegator\n [9]: https://david-dm.org/Raynos/dom-delegator.png\n [10]: https://david-dm.org/Raynos/dom-delegator\n [11]: https://ci.testling.com/Raynos/dom-delegator.png\n [12]: https://ci.testling.com/Raynos/dom-delegator\n',readmeFilename:"README.md",_id:"dom-delegator@3.2.2",_from:"dom-delegator@~3.2.2"}},{}],22:[function(require,module,exports){var PREFIX=require("./prefix.js");module.exports=getField;function getField(target,key){return target[PREFIX+key]||{}}},{"./prefix.js":23}],23:[function(require,module,exports){var version=require("../package.json").version;var MAJOR=version.split(".")[0];var PREFIX="_dom-delegator-events-v"+MAJOR+".0.0-";module.exports=PREFIX},{"../package.json":21}],"html-delegator":[function(require,module,exports){var createDelegator=require("dom-delegator/create-delegator");var HTMLSurface=require("./html-surface.js");module.exports=createDelegator(HTMLSurface)},{"./html-surface.js":9,"dom-delegator/create-delegator":14}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){},{}],TFY9oj:[function(require,module,exports){var split=require("browser-split");var ClassList=require("class-list");var DataSet=require("data-set");require("html-element");function context(){var cleanupFuncs=[];function h(){var args=[].slice.call(arguments),e=null;function item(l){var r;function parseClass(string){var m=split(string,/([\.#]?[a-zA-Z0-9_:-]+)/);if(/^\.|#/.test(m[1]))e=document.createElement("div");forEach(m,function(v){var s=v.substring(1,v.length);if(!v)return;if(!e)e=document.createElement(v);else if(v[0]===".")ClassList(e).add(s);else if(v[0]==="#")e.setAttribute("id",s)})}if(l==null);else if("string"===typeof l){if(!e)parseClass(l);else e.appendChild(r=document.createTextNode(l))}else if("number"===typeof l||"boolean"===typeof l||l instanceof Date||l instanceof RegExp){e.appendChild(r=document.createTextNode(l.toString()))}else if(isArray(l))forEach(l,item);else if(isNode(l))e.appendChild(r=l);else if(l instanceof Text)e.appendChild(r=l);else if("object"===typeof l){for(var k in l){if("function"===typeof l[k]){if(/^on\w+/.test(k)){if(e.addEventListener){e.addEventListener(k.substring(2),l[k],false);cleanupFuncs.push(function(){e.removeEventListener(k.substring(2),l[k],false)})}else{e.attachEvent(k,l[k]);cleanupFuncs.push(function(){e.detachEvent(k,l[k])})}}else{e[k]=l[k]();cleanupFuncs.push(l[k](function(v){e[k]=v}))}}else if(k==="style"){if("string"===typeof l[k]){e.style.cssText=l[k]}else{for(var s in l[k])(function(s,v){if("function"===typeof v){e.style.setProperty(s,v());cleanupFuncs.push(v(function(val){e.style.setProperty(s,val)}))}else e.style.setProperty(s,l[k][s])})(s,l[k][s])}}else if(k.substr(0,5)==="data-"){DataSet(e)[k.substr(5)]=l[k]}else{e[k]=l[k]}}}else if("function"===typeof l){var v=l();e.appendChild(r=isNode(v)?v:document.createTextNode(v));cleanupFuncs.push(l(function(v){if(isNode(v)&&r.parentElement)r.parentElement.replaceChild(v,r),r=v;else r.textContent=v}))}return r}while(args.length)item(args.shift());return e}h.cleanup=function(){for(var i=0;i<cleanupFuncs.length;i++){cleanupFuncs[i]()}};return h}var h=module.exports=context();h.context=context;function isNode(el){return el&&el.nodeName&&el.nodeType}function isText(el){return el&&el.nodeName==="#text"&&el.nodeType==3}function forEach(arr,fn){if(arr.forEach)return arr.forEach(fn);for(var i=0;i<arr.length;i++)fn(arr[i],i)}function isArray(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{"browser-split":4,"class-list":5,"data-set":7,"html-element":1}],hyperscript:[function(require,module,exports){module.exports=require("TFY9oj")},{}],4:[function(require,module,exports){module.exports=function split(undef){var nativeSplit=String.prototype.split,compliantExecNpcg=/()??/.exec("")[1]===undef,self;self=function(str,separator,limit){if(Object.prototype.toString.call(separator)!=="[object RegExp]"){return nativeSplit.call(str,separator,limit)}var output=[],flags=(separator.ignoreCase?"i":"")+(separator.multiline?"m":"")+(separator.extended?"x":"")+(separator.sticky?"y":""),lastLastIndex=0,separator=new RegExp(separator.source,flags+"g"),separator2,match,lastIndex,lastLength;str+="";if(!compliantExecNpcg){separator2=new RegExp("^"+separator.source+"$(?!\\s)",flags)}limit=limit===undef?-1>>>0:limit>>>0;while(match=separator.exec(str)){lastIndex=match.index+match[0].length;if(lastIndex>lastLastIndex){output.push(str.slice(lastLastIndex,match.index));if(!compliantExecNpcg&&match.length>1){match[0].replace(separator2,function(){for(var i=1;i<arguments.length-2;i++){if(arguments[i]===undef){match[i]=undef}}})}if(match.length>1&&match.index<str.length){Array.prototype.push.apply(output,match.slice(1))}lastLength=match[0].length;lastLastIndex=lastIndex;if(output.length>=limit){break}}if(separator.lastIndex===match.index){separator.lastIndex++}}if(lastLastIndex===str.length){if(lastLength||!separator.test("")){output.push("")}}else{output.push(str.slice(lastLastIndex))}return output.length>limit?output.slice(0,limit):output};return self}()},{}],5:[function(require,module,exports){var indexof=require("indexof");module.exports=ClassList;function ClassList(elem){var cl=elem.classList;if(cl){return cl}var classList={add:add,remove:remove,contains:contains,toggle:toggle,toString:$toString,length:0,item:item};return classList;function add(token){var list=getTokens();if(indexof(list,token)>-1){return}list.push(token);setTokens(list)}function remove(token){var list=getTokens(),index=indexof(list,token);if(index===-1){return}list.splice(index,1);setTokens(list)}function contains(token){return indexof(getTokens(),token)>-1}function toggle(token){if(contains(token)){remove(token);return false}else{add(token);return true}}function $toString(){return elem.className}function item(index){var tokens=getTokens();return tokens[index]||null}function getTokens(){var className=elem.className;return filter(className.split(" "),isTruthy)}function setTokens(list){var length=list.length;elem.className=list.join(" ");classList.length=length;for(var i=0;i<list.length;i++){classList[i]=list[i]}delete list[length]}}function filter(arr,fn){var ret=[];for(var i=0;i<arr.length;i++){if(fn(arr[i]))ret.push(arr[i])}return ret}function isTruthy(value){return!!value}},{indexof:6}],6:[function(require,module,exports){var indexOf=[].indexOf;module.exports=function(arr,obj){if(indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],7:[function(require,module,exports){var Weakmap=require("weakmap");var Individual=require("individual");var datasetMap=Individual("__DATA_SET_WEAKMAP",Weakmap());module.exports=DataSet;function DataSet(elem){if(elem.dataset){return elem.dataset}var hash=datasetMap.get(elem);if(!hash){hash=createHash(elem);datasetMap.set(elem,hash)}return hash}function createHash(elem){var attributes=elem.attributes;var hash={};if(attributes===null||attributes===undefined){return hash}for(var i=0;i<attributes.length;i++){var attr=attributes[i];if(attr.name.substr(0,5)!=="data-"){continue}hash[attr.name.substr(5)]=attr.value}return hash}},{individual:8,weakmap:10}],8:[function(require,module,exports){var root=require("global");module.exports=Individual;function Individual(key,value){if(root[key]){return root[key]}Object.defineProperty(root,key,{value:value,configurable:true});return value}},{global:9}],9:[function(require,module,exports){(function(global){if(typeof global!=="undefined"){module.exports=global}else if(typeof window!=="undefined"){module.exports=window}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],10:[function(require,module,exports){void function(global,undefined_,undefined){var getProps=Object.getOwnPropertyNames,defProp=Object.defineProperty,toSource=Function.prototype.toString,create=Object.create,hasOwn=Object.prototype.hasOwnProperty,funcName=/^\n?function\s?(\w*)?_?\(/;function define(object,key,value){if(typeof key==="function"){value=key;key=nameOf(value).replace(/_$/,"")}return defProp(object,key,{configurable:true,writable:true,value:value})}function nameOf(func){return typeof func!=="function"?"":"name"in func?func.name:toSource.call(func).match(funcName)[1]}var Data=function(){var dataDesc={value:{writable:true,value:undefined}},datalock="return function(k){if(k===s)return l}",uids=create(null),createUID=function(){var key=Math.random().toString(36).slice(2);return key in uids?createUID():uids[key]=key},globalID=createUID(),storage=function(obj){if(hasOwn.call(obj,globalID))return obj[globalID];if(!Object.isExtensible(obj))throw new TypeError("Object must be extensible");var store=create(null);defProp(obj,globalID,{value:store});return store};define(Object,function getOwnPropertyNames(obj){var props=getProps(obj);if(hasOwn.call(obj,globalID))props.splice(props.indexOf(globalID),1);return props});function Data(){var puid=createUID(),secret={};this.unlock=function(obj){var store=storage(obj);if(hasOwn.call(store,puid))return store[puid](secret);var data=create(null,dataDesc);defProp(store,puid,{value:new Function("s","l",datalock)(secret,data)});return data}}define(Data.prototype,function get(o){return this.unlock(o).value});define(Data.prototype,function set(o,v){this.unlock(o).value=v});return Data}();var WM=function(data){var validate=function(key){if(key==null||typeof key!=="object"&&typeof key!=="function")throw new TypeError("Invalid WeakMap key")};var wrap=function(collection,value){var store=data.unlock(collection);if(store.value)throw new TypeError("Object is already a WeakMap");store.value=value};var unwrap=function(collection){var storage=data.unlock(collection).value;if(!storage)throw new TypeError("WeakMap is not generic");return storage};var initialize=function(weakmap,iterable){if(iterable!==null&&typeof iterable==="object"&&typeof iterable.forEach==="function"){iterable.forEach(function(item,i){if(item instanceof Array&&item.length===2)set.call(weakmap,iterable[i][0],iterable[i][1])})}};function WeakMap(iterable){if(this===global||this==null||this===WeakMap.prototype)return new WeakMap(iterable);wrap(this,new Data);initialize(this,iterable)}function get(key){validate(key);var value=unwrap(this).get(key);return value===undefined_?undefined:value}function set(key,value){validate(key);unwrap(this).set(key,value===undefined?undefined_:value)}function has(key){validate(key);return unwrap(this).get(key)!==undefined}function delete_(key){validate(key);var data=unwrap(this),had=data.get(key)!==undefined;data.set(key,undefined);return had}function toString(){unwrap(this);return"[object WeakMap]"}try{var src=("return "+delete_).replace("e_","\\u0065"),del=new Function("unwrap","validate",src)(unwrap,validate)}catch(e){var del=delete_}var src=(""+Object).split("Object");var stringifier=function toString(){return src[0]+nameOf(this)+src[1]};define(stringifier,stringifier);var prep={__proto__:[]}instanceof Array?function(f){f.__proto__=stringifier}:function(f){define(f,stringifier)};prep(WeakMap);[toString,get,set,has,del].forEach(function(method){define(WeakMap.prototype,method);prep(method)});return WeakMap}(new Data);var defaultCreator=Object.create?function(){return Object.create(null)}:function(){return{}};function createStorage(creator){var weakmap=new WM;creator||(creator=defaultCreator);function storage(object,value){if(value||arguments.length===2){weakmap.set(object,value)}else{value=weakmap.get(object);if(value===undefined){value=creator(object);weakmap.set(object,value)}}return value}return storage}if(typeof module!=="undefined"){module.exports=WM}else if(typeof exports!=="undefined"){exports.WeakMap=WM}else if(!("WeakMap"in global)){global.WeakMap=WM}WM.createStorage=createStorage;if(global.WeakMap)global.WeakMap.createStorage=createStorage}((0,eval)("this"))},{}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var getField=require("./symbol/get-field.js");var setField=require("./symbol/set-field.js");module.exports=addEvent;function addEvent(target,type,sink,data){var id=sink.id;var events=getField(target,id);sink.dispatch=dispatch;events[type]=[data,sink];setField(target,id,events)}function dispatch(listener,ev){var sink=listener.sink;sink.write({value:listener.data,ev:null})}},{"./symbol/get-field.js":3,"./symbol/set-field.js":5}],2:[function(require,module,exports){module.exports={name:"dom-delegator",version:"3.2.2",description:"Decorate elements with delegated events",keywords:[],author:{name:"Raynos",email:"raynos2@gmail.com"},repository:{type:"git",url:"git://github.com/Raynos/dom-delegator.git"},main:"index",homepage:"https://github.com/Raynos/dom-delegator",contributors:[{name:"Raynos"}],bugs:{url:"https://github.com/Raynos/dom-delegator/issues",email:"raynos2@gmail.com"},dependencies:{global:"~2.0.7",uuid:"~1.4.1"},devDependencies:{tape:"~2.4.2",hyperscript:"~1.4.0","synthetic-dom-events":"~0.1.1",testling:"~1.6.0","event-sinks":"~1.0.1"},licenses:[{type:"MIT",url:"http://github.com/Raynos/dom-delegator/raw/master/LICENSE"}],scripts:{test:"node ./test/index.js",start:"node ./index.js",watch:"nodemon -w ./index.js index.js","travis-test":"istanbul cover ./test/index.js && ((cat coverage/lcov.info | coveralls) || exit 0)",cover:"istanbul cover --report none --print detail ./test/index.js","view-cover":"istanbul report html && google-chrome ./coverage/index.html","test-browser":"testem-browser ./test/browser/index.js",testem:"testem-both -b=./test/browser/index.js"},testling:{files:"test/index.js",browsers:["ie/8..latest","firefox/16..latest","firefox/nightly","chrome/22..latest","chrome/canary","opera/12..latest","opera/next","safari/5.1..latest","ipad/6.0..latest","iphone/6.0..latest","android-browser/4.2..latest"]},readme:'# dom-delegator\n\n<!--\n [![build status][1]][2]\n [![NPM version][3]][4]\n [![Coverage Status][5]][6]\n [![gemnasium Dependency Status][7]][8]\n [![Davis Dependency status][9]][10]\n-->\n\n<!-- [![browser support][11]][12] -->\n\nDecorate elements with delegated events\n\n## Motivation\n\nWhen building a web application you don\'t want to deal with\n messing around with the DOM directly if you can avoid it.\n\nWhat you really want to do is write application logic. Generally\n how application logic works is that you react to some kind of\n user input, run some logic and maybe change some state.\n\nLet\'s take a look at a calendar example. For a calendar we just\n want to react to a bunch of date change events and update the\n state of the calendar accordingly. We don\'t really care what\n triggers the date change events.\n\n```js\nvar Calendar = function () {\n var calendarState = { ... }\n var calendarInputs = { ... }\n\n calendarInputs.dateChange(function (newDate) {\n var d = new Date(newDate)\n\n calendarState.theTime.set(d)\n })\n}\n```\n\nThe above code is basically the application logic you want to\n express. Now imagine we had some kind of data binding that\n re-rendered the template / view for the calendar each time\n we update the calendarState.\n\n```js\nfunction render(calendarState) {\n var WEEK = 1000 * 60 * 60 * 24 * 7\n var prevWeek = +calendarState.theTime - WEEK\n var nextWeek = +calendarState.theTime + WEEK\n\n return h("div", [\n h("table", calendarGrid(calendarState)),\n h("div.controls", [\n h("button.prev", {\n "data-click": "dateChange:" + prevWeek\n }, "previous week"),\n h("button.next", {\n "data-click": "dateChange:" + nextWeek\n }, "next week")\n ])\n ])\n}\n```\n\nSomething will need to trigger the date change events, since we\n don\'t want to write any manual DOM code and since we already\n have a reactive templating system we should just add hooks to\n our templates that say when this DOM event occurs I want you\n to trigger this "meaningful" event in my system\n\n### Other motivations\n\n - solution should be a module, not a framework\n - solution should work recursively without namespace conflicts\n - solution should use event delegation, it shouldnt require\n binding to each DOM element manually\n - solution should allow rendering logic to be seperate from\n input handling logic.\n - solution doesn\'t require passing concrete functions to the\n rendering logic. The rendering and input handling most\n be loosely coupled.\n - solution should allow passing data to the event listener.\n - solution should discourage passing a DOM Event object to\n listener. You shouldn\'t read the `ev` or `ev.target` in\n your input handling code\n - library should only do input handling. Not input handling AND\n reactive rendering.\n\n## Example DOM\n\n```js\nvar document = require("global/document")\nvar Delegator = require("dom-delegator")\nvar h = require("hyperscript")\nvar addEvent = require("dom-delegator/add-event")\nvar EventSinks = require("event-sinks/geval")\n\nvar delegator = Delegator(document.body)\nvar events = EventSinks(delegator.id, ["textClicked"])\nvar sinks = events.sinks\nvar elem = h("div.foo", [\n h("div.bar", "bar"),\n h("span.baz", "baz")\n])\nvar bar = elem.querySelector(".bar")\nvar baz = elem.querySelector(".baz")\ndocument.body.appendChild(elem)\n\n\n// add individual elems.\naddEvent(bar, "click", sinks.textClicked, {\n type: "bar"\n})\naddEvent(baz, "click", sinks.textClicked, {\n type: "baz"\n})\n\nevents.textClicked(function (tuple) {\n var value = tuple.value\n\n console.log("doSomething", value.type)\n})\n```\n\n## Example data- attributes (Not working yet)\n\n```js\nvar document = require("global/document")\nvar Delegator = require("dom-delegator")\nvar h = require("hyperscript")\nvar event = require("dom-delegator/event")\nvar EventSinks = require("event-sinks/geval")\n\nvar delegator = Delegator(document.body)\nvar events = EventSinks(delegator.id, ["textClicked"])\nvar sinks = events.sinks\n\nvar elem = h("div.foo", [\n h("div.bar", { \n "data-click": event(sinks.textClicked, { type: "bar" })\n }, "bar"),\n h("div.baz", {\n "data-click": event(sinks.textClicked, { type: "baz" })\n }, "baz")\n])\ndocument.body.appendChild(elem)\n\ndelegator.textClicked(function (tuple) {\n var value = tuple.value\n\n console.log("doSomething", value.type)\n})\n```\n\n## Concept. (Not working)\n\nThe concept behind `dom-delegator` is to seperate declaring\n which UI elements trigger well named user input events from \n the event handling.\n\nFor example you might have an `input.js` where you handle user\n input, based on well named, non-DOM specific events.\n\n```js\n// input.js\nmodule.exports = Input\n\nfunction Input(state, sources) {\n // when the input event todo addition occurs\n // create a fresh item and add it\n sources.todoAdded(function (data, ev) {\n var value = ev.currentValue\n var todo = { title: value, completed: false }\n state.todos.push(todo)\n })\n\n // when the input event todo removal occurs\n // find the item and delete it from the list\n sources.todoRemoved(function (data, ev) {\n var id = data\n var index = -1\n state.todos.some(function (todo, itemIndex) {\n if (todo.id() === id) {\n index = itemIndex\n return true\n }\n })\n\n state.todos.splice(index, 1)\n })\n}\n```\n\nOne thing to notice here is that the input handling is coupled\n to keypress or click events. Those are implementation details\n of the declarative UI. The input handling has been described \n in a loosely coupled way.\n\nThe only coupling is that addition is based on the current value\n of the UI element that triggered the `todoAdded` event.\n\nSince we have defined our input handling, we now need to add\n the declarative event hooks to our UI.\n\nWe will use `HTML` and the `data- attributes` style interface\n for the delegator\n\n```html\n// ui.html\n<ul>\n <li data-id="4">\n <span class="todo-title">Some todo</span>\n <button data-click="todoRemoved:4">Remove</button>\n </li>\n</ul>\n<input class="add-todo" name="title" data-submit="todoAdded" />\n```\n\nHere we have decorated the todo item UI with a click event.\n whenever it is clicked it will emit the `todoRemoved` event\n and data will be set to the value after the `:` in this case\n `4`.\n\nWe also decorated the input with the `todoAdded` event.\n\nThe contract between the input handler and the UI is fairly\n loosely defined and it should be possible to refactor the UI\n without breaking the input handler. You can make the\n `todoAdded` event more generic like:\n\n```html\n// ui.html\n\n<div class="todo-addition" data-submit="todoAdded">\n <input class="add-todo" name="title" />\n</div>\n```\n\nThen update the input handler\n\n```js\n// when the input event todo addition occurs\n// create a fresh item and add it\ndelegator.sources.todoAdded(function (tuple) {\n var ev = tuple.ev\n var title = ev.currentValue.title\n var todo = { title: title, completed: false }\n state.todos.push(todo)\n})\n```\n\nWe have now bound the `todoAdded` event less tightly to \n `currentValue` and as long as there is some kind of `input`\n or `textarea` or `custom element` with a name called `\'title\'`\n the input handling code will still work.\n\n## Custom events (Not implemented)\n\nThe `type: "submit"` or `data-submit` event and the\n `type: "change"` or `data-change` event are not the normal\n DOM events for `addEventListener(\'submit\')` or \n `addEventListener(\'change\')` \n\n`data-submit` and `data-change` actually have more complex\n semantics. They can be bound to a container and well then\n emit the named event every time any child changes by the\n submit or change semantics.\n\nIf bound to a container it will use `FormData(...)` to read\n the currentValue as a hash of name to value of elements.\n\nIf bound to a single element it will get the value of that \n element based on what kind of element it is.\n\n### submit semantics\n\n`submit` triggers on `keypress` if the key is ENTER or triggers\n on a click if the click target is a `button` or `input` of \n type `"submit"`\n\n### change semantics\n\n`change` triggers on `change` (DOM change event) or on `keypress`\n\n## Installation\n\n`npm install dom-delegator`\n\n## Contributors\n\n - Raynos\n\n## MIT Licenced\n\n [1]: https://secure.travis-ci.org/Raynos/dom-delegator.png\n [2]: https://travis-ci.org/Raynos/dom-delegator\n [3]: https://badge.fury.io/js/dom-delegator.png\n [4]: https://badge.fury.io/js/dom-delegator\n [5]: https://coveralls.io/repos/Raynos/dom-delegator/badge.png\n [6]: https://coveralls.io/r/Raynos/dom-delegator\n [7]: https://gemnasium.com/Raynos/dom-delegator.png\n [8]: https://gemnasium.com/Raynos/dom-delegator\n [9]: https://david-dm.org/Raynos/dom-delegator.png\n [10]: https://david-dm.org/Raynos/dom-delegator\n [11]: https://ci.testling.com/Raynos/dom-delegator.png\n [12]: https://ci.testling.com/Raynos/dom-delegator\n',readmeFilename:"README.md",_id:"dom-delegator@3.2.2",dist:{shasum:"00bda5a1fa79a89a9a19b7122fc6ce5a768ca60c"},_from:"dom-delegator@~3.2.2",_resolved:"https://registry.npmjs.org/dom-delegator/-/dom-delegator-3.2.2.tgz"}
},{}],3:[function(require,module,exports){var PREFIX=require("./prefix.js");module.exports=getField;function getField(target,key){return target[PREFIX+key]||{}}},{"./prefix.js":4}],4:[function(require,module,exports){var version=require("../package.json").version;var MAJOR=version.split(".")[0];var PREFIX="_dom-delegator-events-v"+MAJOR+".0.0-";module.exports=PREFIX},{"../package.json":2}],5:[function(require,module,exports){var PREFIX=require("./prefix.js");module.exports=setField;function setField(target,key,value){Object.defineProperty(target,PREFIX+key,{value:value,writable:false,enumerable:false,configurable:true})}},{"./prefix.js":4}],"html-delegator/add-event":[function(require,module,exports){module.exports=require("dom-delegator/add-event")},{"dom-delegator/add-event":1}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{throw TypeError('Uncaught, unspecified "error" event.')}return false}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);console.trace()}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],GfMX47:[function(require,module,exports){var EventEmitter=require("events").EventEmitter;var Sink=require("./sink");var cuid=require("cuid");module.exports=EventSinks;function EventSinks(id,names){if(Array.isArray(id)){names=id;id=cuid()}var emitter=new EventEmitter;var sinks=names.reduce(function(acc,key){acc[key]=new Sink(emitter.emit.bind(emitter,key),id,key);return acc},{});return{emitter:emitter,sinks:sinks}}},{"./sink":5,cuid:4,events:1}],"event-sinks":[function(require,module,exports){module.exports=require("GfMX47")},{}],4:[function(require,module,exports){(function(app){"use strict";var namespace="cuid",c=0,blockSize=4,base=36,discreteValues=Math.pow(base,blockSize),pad=function pad(num,size){var s="000000000"+num;return s.substr(s.length-size)},randomBlock=function randomBlock(){return pad((Math.random()*discreteValues<<0).toString(base),blockSize)},safeCounter=function(){c=c<discreteValues?c:0;c++;return c-1},api=function cuid(){var letter="c",timestamp=(new Date).getTime().toString(base),counter,fingerprint=api.fingerprint(),random=randomBlock()+randomBlock();counter=pad(safeCounter().toString(base),blockSize);return letter+timestamp+counter+fingerprint+random};api.slug=function slug(){var date=(new Date).getTime().toString(36),counter,print=api.fingerprint().slice(0,1)+api.fingerprint().slice(-1),random=randomBlock().slice(-2);counter=safeCounter().toString(36).slice(-4);return date.slice(-2)+counter+print+random};api.globalCount=function globalCount(){var cache=function calc(){var i,count=0;for(i in window){count++}return count}();api.globalCount=function(){return cache};return cache};api.fingerprint=function browserPrint(){return pad((navigator.mimeTypes.length+navigator.userAgent.length).toString(36)+api.globalCount().toString(36),4)};if(app.register){app.register(namespace,api)}else if(typeof module!=="undefined"){module.exports=api}else{app[namespace]=api}})(this.applitude||this)},{}],5:[function(require,module,exports){module.exports=Sink;function Sink(write,id,key){if(!(this instanceof Sink)){return new Sink(write,id,key)}this.id=id||"";this.key=key||"";this.write=write}},{}]},{},[]);var document=require("global").document;var Delegator=require("html-delegator");var h=require("hyperscript");var addEvent=require("html-delegator/add-event");var EventSinks=require("event-sinks");var delegator=Delegator(document.body);var inputs=EventSinks(delegator.id,["textClicked"]);var emitter=inputs.emitter;var sinks=inputs.sinks;var elem=h("div.foo",[h("div.bar","bar"),h("span.baz","baz")]);var bar=elem.querySelector(".bar");var baz=elem.querySelector(".baz");document.body.appendChild(elem);addEvent(bar,"click",sinks.textClicked,{type:"bar"});addEvent(baz,"click",sinks.textClicked,{type:"baz"});emitter.on("textClicked",function(tuple){var value=tuple.value;console.log("doSomething",value.type)});
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"global": "4.2.1",
"html-delegator": "1.0.1",
"hyperscript": "1.4.0",
"event-sinks": "2.2.0"
}
}
<style type='text/css'>html, body { margin: 0; padding: 0; border: 0; }
body, html { height: 100%; width: 100%; }</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment