Skip to content

Instantly share code, notes, and snippets.

@brianberlin
Created September 27, 2014 03:42
Show Gist options
  • Save brianberlin/9571bff8b86ababbea53 to your computer and use it in GitHub Desktop.
Save brianberlin/9571bff8b86ababbea53 to your computer and use it in GitHub Desktop.
requirebin sketch
var View = require('ampersand-view'),
domReady = require('domready');
var MyView = View.extend({
el: document.body,
template: "<div><div data-hook='last-clicked'></div><a data-hook='test1'>Test 1</a><a data-hook='test2'>Test 2</a></div>",
events: {
'click [data-hook=test1]': 'testOne',
'click [data-hook=test2]': 'testTwo',
},
props: {
lastClicked: { type: 'string' },
},
testOne: function () {
this.lastClicked = 'test1';
},
testTwo: function () {
this.lastClicked = 'test2';
}
});
domReady(function () {
window.view = new MyView();
});
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}({domready:[function(require,module,exports){!function(name,definition){if(typeof module!="undefined")module.exports=definition();else if(typeof define=="function"&&typeof define.amd=="object")define(definition);else this[name]=definition()}("domready",function(){var fns=[],listener,doc=document,hack=doc.documentElement.doScroll,domContentLoaded="DOMContentLoaded",loaded=(hack?/^loaded|^c/:/^loaded|^i|^c/).test(doc.readyState);if(!loaded)doc.addEventListener(domContentLoaded,listener=function(){doc.removeEventListener(domContentLoaded,listener);loaded=1;while(listener=fns.shift())listener()});return function(fn){loaded?fn():fns.push(fn)}})},{}]},{},[]);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 _=require("underscore");var BBEvents=require("backbone-events-standalone");var ampExtend=require("ampersand-class-extend");var options=["collection","el","viewOptions","view","filter","reverse","parent"];function CollectionView(spec){if(!spec){throw new ReferenceError("Collection view missing required parameters: collection, el")}if(!spec.collection){throw new ReferenceError("Collection view requires a collection")}if(!spec.el){throw new ReferenceError("Collection view requires an el")}_.extend(this,_.pick(spec,options));this.views=[];this.listenTo(this.collection,"add",this._addViewForModel);this.listenTo(this.collection,"remove",this._removeViewForModel);this.listenTo(this.collection,"sort",this._rerenderAll);this.listenTo(this.collection,"refresh reset",this._reset)}_.extend(CollectionView.prototype,BBEvents,{render:function(){this._renderAll();return this},remove:function(){_.invoke(this.views,"remove");this.stopListening()},_getViewByModel:function(model){return _.find(this.views,function(view){return model===view.model})},_createViewForModel:function(model){var view=new this.view(_({model:model,collection:this.collection}).extend(this.viewOptions));this.views.push(view);view.parent=this;view.renderedByParentView=true;view.render();return view},_getOrCreateByModel:function(model){return this._getViewByModel(model)||this._createViewForModel(model)},_addViewForModel:function(model,collection,options){var view=this._getViewByModel(model);var matches=this.filter?this.filter(model):true;if(!matches){return}if(!view){view=new this.view(_({model:model,collection:this.collection}).extend(this.viewOptions));this.views.push(view);view.parent=this;view.renderedByParentView=true;view.render({containerEl:this.el})}if(options&&options.rerender){this._insertView(view)}else{this._insertViewAtIndex(view)}},_insertViewAtIndex:function(view){if(!view.insertSelf){var pos=this.collection.indexOf(view.model);var modelToInsertBefore,viewToInsertBefore;if(this.reverse){modelToInsertBefore=this.collection.at(pos-1)}else{modelToInsertBefore=this.collection.at(pos+1)}viewToInsertBefore=this._getViewByModel(modelToInsertBefore);if(viewToInsertBefore){this.el.insertBefore(view.el,viewToInsertBefore&&viewToInsertBefore.el)}else{this.el.appendChild(view.el)}}},_insertView:function(view){if(!view.insertSelf){if(this.reverse&&this.el.firstChild){this.el.insertBefore(view.el,this.el.firstChild)}else{this.el.appendChild(view.el)}}},_removeViewForModel:function(model){var view=this._getViewByModel(model);if(!view){return}var index=this.views.indexOf(view);if(index!==-1){view=this.views.splice(index,1)[0];this._removeView(view)}},_removeView:function(view){if(view.animateRemove){view.animateRemove()}else{view.remove()}},_renderAll:function(){this.collection.each(this._addViewForModel,this)},_rerenderAll:function(collection,options){options=options||{};this.collection.each(function(model){this._addViewForModel(model,this,_.extend(options,{rerender:true}))},this)},_reset:function(){var newViews=this.collection.map(this._getOrCreateByModel,this);var toRemove=_.difference(this.views,newViews);toRemove.forEach(this._removeView,this);this.views=newViews;this._rerenderAll()}});CollectionView.extend=ampExtend;module.exports=CollectionView},{"ampersand-class-extend":2,"backbone-events-standalone":5,underscore:23}],2:[function(require,module,exports){var objectExtend=require("extend-object");var extend=function(protoProps){var parent=this;var child;var args=[].slice.call(arguments);if(protoProps&&protoProps.hasOwnProperty("constructor")){child=protoProps.constructor}else{child=function(){return parent.apply(this,arguments)}}objectExtend(child,parent);var Surrogate=function(){this.constructor=child};Surrogate.prototype=parent.prototype;child.prototype=new Surrogate;if(protoProps){args.unshift(child.prototype);objectExtend.apply(null,args)}child.__super__=parent.prototype;return child};module.exports=extend},{"extend-object":3}],3:[function(require,module,exports){var arr=[];var each=arr.forEach;var slice=arr.slice;module.exports=function(obj){each.call(slice.call(arguments,1),function(source){if(source){for(var prop in source){obj[prop]=source[prop]}}});return obj}},{}],4:[function(require,module,exports){(function(){var root=this,breaker={},nativeForEach=Array.prototype.forEach,hasOwnProperty=Object.prototype.hasOwnProperty,slice=Array.prototype.slice,idCounter=0;function miniscore(){return{keys:Object.keys||function(obj){if(typeof obj!=="object"&&typeof obj!=="function"||obj===null){throw new TypeError("keys() called on a non-object")}var key,keys=[];for(key in obj){if(obj.hasOwnProperty(key)){keys[keys.length]=key}}return keys},uniqueId:function(prefix){var id=++idCounter+"";return prefix?prefix+id:id},has:function(obj,key){return hasOwnProperty.call(obj,key)},each:function(obj,iterator,context){if(obj==null)return;if(nativeForEach&&obj.forEach===nativeForEach){obj.forEach(iterator,context)}else if(obj.length===+obj.length){for(var i=0,l=obj.length;i<l;i++){if(iterator.call(context,obj[i],i,obj)===breaker)return}}else{for(var key in obj){if(this.has(obj,key)){if(iterator.call(context,obj[key],key,obj)===breaker)return}}}},once:function(func){var ran=false,memo;return function(){if(ran)return memo;ran=true;memo=func.apply(this,arguments);func=null;return memo}}}}var _=miniscore(),Events;Events={on:function(name,callback,context){if(!eventsApi(this,"on",name,[callback,context])||!callback)return this;this._events||(this._events={});var events=this._events[name]||(this._events[name]=[]);events.push({callback:callback,context:context,ctx:context||this});return this},once:function(name,callback,context){if(!eventsApi(this,"once",name,[callback,context])||!callback)return this;var self=this;var once=_.once(function(){self.off(name,once);callback.apply(this,arguments)});once._callback=callback;return this.on(name,once,context)},off:function(name,callback,context){var retain,ev,events,names,i,l,j,k;if(!this._events||!eventsApi(this,"off",name,[callback,context]))return this;if(!name&&!callback&&!context){this._events={};return this}names=name?[name]:_.keys(this._events);for(i=0,l=names.length;i<l;i++){name=names[i];if(events=this._events[name]){this._events[name]=retain=[];if(callback||context){for(j=0,k=events.length;j<k;j++){ev=events[j];if(callback&&callback!==ev.callback&&callback!==ev.callback._callback||context&&context!==ev.context){retain.push(ev)}}}if(!retain.length)delete this._events[name]}}return this},trigger:function(name){if(!this._events)return this;var args=slice.call(arguments,1);if(!eventsApi(this,"trigger",name,args))return this;var events=this._events[name];var allEvents=this._events.all;if(events)triggerEvents(events,args);if(allEvents)triggerEvents(allEvents,arguments);return this},stopListening:function(obj,name,callback){var listeners=this._listeners;if(!listeners)return this;var deleteListener=!name&&!callback;if(typeof name==="object")callback=this;if(obj)(listeners={})[obj._listenerId]=obj;for(var id in listeners){listeners[id].off(name,callback,this);if(deleteListener)delete this._listeners[id]}return this}};var eventSplitter=/\s+/;var eventsApi=function(obj,action,name,rest){if(!name)return true;if(typeof name==="object"){for(var key in name){obj[action].apply(obj,[key,name[key]].concat(rest))}return false}if(eventSplitter.test(name)){var names=name.split(eventSplitter);for(var i=0,l=names.length;i<l;i++){obj[action].apply(obj,[names[i]].concat(rest))}return false}return true};var triggerEvents=function(events,args){var ev,i=-1,l=events.length,a1=args[0],a2=args[1],a3=args[2];switch(args.length){case 0:while(++i<l)(ev=events[i]).callback.call(ev.ctx);return;case 1:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1);return;case 2:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2);return;case 3:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2,a3);return;default:while(++i<l)(ev=events[i]).callback.apply(ev.ctx,args)}};var listenMethods={listenTo:"on",listenToOnce:"once"};_.each(listenMethods,function(implementation,method){Events[method]=function(obj,name,callback){var listeners=this._listeners||(this._listeners={});var id=obj._listenerId||(obj._listenerId=_.uniqueId("l"));listeners[id]=obj;if(typeof name==="object")callback=this;obj[implementation](name,callback,this);return this}});Events.bind=Events.on;Events.unbind=Events.off;Events.mixin=function(proto){var exports=["on","once","off","trigger","stopListening","listenTo","listenToOnce","bind","unbind"];_.each(exports,function(name){proto[name]=this[name]},this);return proto};if(typeof define==="function"){define(function(){return Events})}else if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){exports=module.exports=Events}exports.BackboneEvents=Events}else{root.BackboneEvents=Events}})(this)},{}],5:[function(require,module,exports){module.exports=require("./backbone-events-standalone")},{"./backbone-events-standalone":4}],6:[function(require,module,exports){var Store=require("key-tree-store");var isArray=require("is-array");var dom=require("ampersand-dom");var matchesSelector=require("matches-selector");module.exports=function(bindings){var store=new Store;var key,current;for(key in bindings){current=bindings[key];if(typeof current==="string"){store.add(key,getBindingFunc({type:"text",selector:current}))}else if(current.forEach){current.forEach(function(binding){store.add(key,getBindingFunc(binding))})}else{store.add(key,getBindingFunc(current))}}return store};var slice=Array.prototype.slice;function getMatches(el,selector,func){if(selector==="")return[el];var matches=[];if(matchesSelector(el,selector))matches.push(el);return matches.concat(slice.call(el.querySelectorAll(selector)))}function makeArray(val){return Array.isArray(val)?val:[val]}function getBindingFunc(binding){var type=binding.type||"text";var hasSelector=true;var selector=function(){if(typeof binding.selector==="string"){return binding.selector}else if(binding.hook){return'[data-hook="'+binding.hook+'"]'}else{return""}}();var previousValue="";if(type==="text"){return function(el,value){getMatches(el,selector).forEach(function(match){dom.text(match,value)})}}else if(type==="class"){return function(el,value){getMatches(el,selector).forEach(function(match){dom.switchClass(match,previousValue,value)});previousValue=value}}else if(type==="attribute"){if(!binding.name)throw Error('attribute bindings must have a "name"');return function(el,value){var names=makeArray(binding.name);getMatches(el,selector).forEach(function(match){names.forEach(function(name){dom.setAttribute(match,name,value)})});previousValue=value}}else if(type==="value"){return function(el,value){getMatches(el,selector).forEach(function(match){if(!value&&value!==0)value="";if(document.activeElement!==match)match.value=value});previousValue=value}}else if(type==="booleanClass"){if(binding.no){return function(el,value,keyName){var yes=makeArray(binding.name||binding.yes||keyName);var no=makeArray(binding.no);var prevClass=value?no:yes;var newClass=value?yes:no;getMatches(el,selector).forEach(function(match){prevClass.forEach(function(pc){dom.removeClass(match,pc)});newClass.forEach(function(nc){dom.addClass(match,nc)})})}}else{return function(el,value,keyName){var name=makeArray(binding.name||keyName);getMatches(el,selector).forEach(function(match){name.forEach(function(className){dom[value?"addClass":"removeClass"](match,className)})})}}}else if(type==="booleanAttribute"){return function(el,value,keyName){var name=makeArray(binding.name||keyName);getMatches(el,selector).forEach(function(match){name.forEach(function(attr){dom[value?"addAttribute":"removeAttribute"](match,attr)})})}}else if(type==="toggle"){if(binding.yes&&binding.no){return function(el,value){getMatches(el,binding.yes).forEach(function(match){dom[value?"show":"hide"](match)});getMatches(el,binding.no).forEach(function(match){dom[value?"hide":"show"](match)})}}else{return function(el,value){getMatches(el,selector).forEach(function(match){dom[value?"show":"hide"](match)})}}}else if(type==="switch"){if(!binding.cases)throw Error('switch bindings must have "cases"');return function(el,value){for(var item in binding.cases){getMatches(el,binding.cases[item]).forEach(function(match){dom[value===item?"show":"hide"](match)})}}}else if(type==="innerHTML"){return function(el,value){getMatches(el,selector).forEach(function(match){dom.html(match,value)})}}else{throw new Error("no such binding type: "+type)}}},{"ampersand-dom":7,"is-array":8,"key-tree-store":9,"matches-selector":22}],7:[function(require,module,exports){var dom=module.exports={text:function(el,val){el.textContent=getString(val)},addClass:function(el,cls){cls=getString(cls);if(!cls)return;if(el.classList){el.classList.add(cls)}else{if(!hasClass(el,cls)){if(el.classList){el.classList.add(cls)}else{el.className+=" "+cls}}}},removeClass:function(el,cls){if(el.classList){el.classList.remove(getString(cls))}else{el.className=el.className.replace(new RegExp("(^|\\b)"+cls.split(" ").join("|")+"(\\b|$)","gi")," ")}},hasClass:hasClass,switchClass:function(el,prevCls,newCls){if(prevCls)this.removeClass(el,prevCls);this.addClass(el,newCls)},addAttribute:function(el,attr){el.setAttribute(attr,"")},removeAttribute:function(el,attr){el.removeAttribute(attr)},setAttribute:function(el,attr,value){el.setAttribute(attr,getString(value))},getAttribute:function(el,attr){return el.getAttribute(attr)},hide:function(el){if(!isHidden(el)){storeDisplayStyle(el);hide(el)}},show:function(el){show(el)},html:function(el,content){el.innerHTML=content}};function getString(val){if(!val&&val!==0){return""}else{return val}}function hasClass(el,cls){if(el.classList){return el.classList.contains(cls)}else{return new RegExp("(^| )"+cls+"( |$)","gi").test(el.className)}}function isHidden(el){return dom.getAttribute(el,"data-anddom-hidden")==="true"}function storeDisplayStyle(el){dom.setAttribute(el,"data-anddom-display",el.style.display)}function show(el){el.style.display=dom.getAttribute(el,"data-anddom-display")||"";dom.removeAttribute(el,"data-anddom-hidden")}function hide(el){dom.setAttribute(el,"data-anddom-hidden","true");el.style.display="none"}},{}],8:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],9:[function(require,module,exports){var slice=Array.prototype.slice;function KeyTreeStore(){this.storage={}}KeyTreeStore.prototype.add=function(keypath,obj){var arr=this.storage[keypath]||(this.storage[keypath]=[]);arr.push(obj)};KeyTreeStore.prototype.remove=function(obj){var path,arr;for(path in this.storage){arr=this.storage[path];arr.some(function(item,index){if(item===obj){arr.splice(index,1);return true}})}};KeyTreeStore.prototype.get=function(keypath){var res=[];var key;for(key in this.storage){if(!keypath||keypath===key||key.indexOf(keypath+".")===0){res=res.concat(this.storage[key])}}return res};KeyTreeStore.prototype.getGrouped=function(keypath){var res={};var key;for(key in this.storage){if(!keypath||keypath===key||key.indexOf(keypath+".")===0){res[key]=slice.call(this.storage[key])}}return res};KeyTreeStore.prototype.getAll=function(keypath){var res={};var key;for(key in this.storage){if(keypath===key||key.indexOf(keypath+".")===0){res[key]=slice.call(this.storage[key])}}return res};KeyTreeStore.prototype.run=function(keypath,context){var args=slice.call(arguments,2);this.get(keypath).forEach(function(fn){fn.apply(context||this,args)})};module.exports=KeyTreeStore},{}],10:[function(require,module,exports){var _=require("underscore");var BBEvents=require("backbone-events-standalone");var KeyTree=require("key-tree-store");var arrayNext=require("array-next");var changeRE=/^change:/;function Base(attrs,options){options||(options={});this.cid||(this.cid=_.uniqueId("state"));this._events={};this._values={};this._definition=Object.create(this._definition);if(options.parse)attrs=this.parse(attrs,options);this.parent=options.parent;this.collection=options.collection;this._keyTree=new KeyTree;this._initCollections();this._initChildren();this._cache={};this._previousAttributes={};if(attrs)this.set(attrs,_.extend({silent:true,initial:true},options));this._changed={};if(this._derived)this._initDerived();if(options.init!==false)this.initialize.apply(this,arguments)}_.extend(Base.prototype,BBEvents,{extraProperties:"ignore",idAttribute:"id",namespaceAttribute:"namespace",typeAttribute:"modelType",initialize:function(){return this},getId:function(){return this[this.idAttribute]},getNamespace:function(){return this[this.namespaceAttribute]},getType:function(){return this[this.typeAttribute]},isNew:function(){return this.getId()==null},escape:function(attr){return _.escape(this.get(attr))},isValid:function(options){return this._validate({},_.extend(options||{},{validate:true}))},parse:function(resp,options){return resp},serialize:function(){var res=this.getAttributes({props:true},true);_.each(this._children,function(value,key){res[key]=this[key].serialize()},this);_.each(this._collections,function(value,key){res[key]=this[key].serialize()},this);return res},set:function(key,value,options){var self=this;var extraProperties=this.extraProperties;var triggers=[];var changing,changes,newType,newVal,def,cast,err,attr,attrs,dataType,silent,unset,currentVal,initial,hasChanged,isEqual;if(_.isObject(key)||key===null){attrs=key;options=value}else{attrs={};attrs[key]=value}options=options||{};if(!this._validate(attrs,options))return false;unset=options.unset;silent=options.silent;initial=options.initial;changes=[];changing=this._changing;this._changing=true;if(!changing){this._previousAttributes=this.attributes;this._changed={}}for(attr in attrs){newVal=attrs[attr];newType=typeof newVal;currentVal=this._values[attr];def=this._definition[attr];if(!def){if(this._children[attr]||this._collections[attr]){this[attr].set(newVal,options);continue}else if(extraProperties==="ignore"){continue}else if(extraProperties==="reject"){throw new TypeError('No "'+attr+'" property defined on '+(this.type||"this")+' model and extraProperties not set to "ignore" or "allow"')}else if(extraProperties==="allow"){def=this._createPropertyDefinition(attr,"any")}}isEqual=this._getCompareForType(def.type);dataType=this._dataTypes[def.type];if(dataType&&dataType.set){cast=dataType.set(newVal);newVal=cast.val;newType=cast.type}if(def.test){err=def.test.call(this,newVal,newType);if(err){throw new TypeError("Property '"+attr+"' failed validation with error: "+err)}}if(_.isUndefined(newVal)&&def.required){throw new TypeError("Required property '"+attr+"' must be of type "+def.type+". Tried to set "+newVal)}if(_.isNull(newVal)&&def.required&&!def.allowNull){throw new TypeError("Property '"+attr+"' must be of type "+def.type+" (cannot be null). Tried to set "+newVal)}if(def.type&&def.type!=="any"&&def.type!==newType&&!_.isNull(newVal)&&!_.isUndefined(newVal)){throw new TypeError("Property '"+attr+"' must be of type "+def.type+". Tried to set "+newVal)}if(def.values&&!_.contains(def.values,newVal)){throw new TypeError("Property '"+attr+"' must be one of values: "+def.values.join(", "))}hasChanged=!isEqual(currentVal,newVal,attr);if(def.setOnce&&currentVal!==undefined&&hasChanged){throw new TypeError("Property '"+key+"' can only be set once.")}if(hasChanged){changes.push({prev:currentVal,val:newVal,key:attr});self._changed[attr]=newVal}else{delete self._changed[attr]}}_.each(changes,function(change){self._previousAttributes[change.key]=change.prev;if(unset){delete self._values[change.key]}else{self._values[change.key]=change.val}});if(!silent&&changes.length)self._pending=true;if(!silent){_.each(changes,function(change){self.trigger("change:"+change.key,self,change.val,options)})}if(changing)return this;if(!silent){while(this._pending){this._pending=false;this.trigger("change",this,options)}}this._pending=false;this._changing=false;return this},get:function(attr){return this[attr]},toggle:function(property){var def=this._definition[property];if(def.type==="boolean"){this[property]=!this[property]}else if(def&&def.values){this[property]=arrayNext(def.values,this[property])}else{throw new TypeError("Can only toggle properties that are type `boolean` or have `values` array.")}return this},previousAttributes:function(){return _.clone(this._previousAttributes)},hasChanged:function(attr){if(attr==null)return!_.isEmpty(this._changed);return _.has(this._changed,attr)},changedAttributes:function(diff){if(!diff)return this.hasChanged()?_.clone(this._changed):false;var val,changed=false;var old=this._changing?this._previousAttributes:this.attributes;var def,isEqual;for(var attr in diff){def=this._definition[attr];isEqual=this._getCompareForType(def&&def.type);if(isEqual(old[attr],val=diff[attr]))continue;(changed||(changed={}))[attr]=val}return changed},toJSON:function(){return this.serialize()},unset:function(attr,options){var def=this._definition[attr];var type=def.type;var val;if(def.required){val=_.result(def,"default");return this.set(attr,val,options)}else{return this.set(attr,val,_.extend({},options,{unset:true}))}},clear:function(options){var self=this;_.each(_.keys(this.attributes),function(key){self.unset(key,options)});return this},previous:function(attr){if(attr==null||!Object.keys(this._previousAttributes).length)return null;return this._previousAttributes[attr]},_getDefaultForType:function(type){var dataType=this._dataTypes[type];return dataType&&dataType.default},_getCompareForType:function(type){var dataType=this._dataTypes[type];if(dataType&&dataType.compare)return _.bind(dataType.compare,this);return _.isEqual},_validate:function(attrs,options){if(!options.validate||!this.validate)return true;attrs=_.extend({},this.attributes,attrs);var error=this.validationError=this.validate(attrs,options)||null;if(!error)return true;this.trigger("invalid",this,error,_.extend(options||{},{validationError:error}));return false},_createPropertyDefinition:function(name,desc,isSession){return createPropertyDefinition(this,name,desc,isSession)},_ensureValidType:function(type){return _.contains(["string","number","boolean","array","object","date","any"].concat(_.keys(this._dataTypes)),type)?type:undefined},getAttributes:function(options,raw){options||(options={});_.defaults(options,{session:false,props:false,derived:false});var res={};var val,item,def;for(item in this._definition){def=this._definition[item];if(options.session&&def.session||options.props&&!def.session){val=raw?this._values[item]:this[item];if(typeof val==="undefined")val=_.result(def,"default");if(typeof val!=="undefined")res[item]=val}}if(options.derived){for(item in this._derived)res[item]=this[item]}return res},_initDerived:function(){var self=this;_.each(this._derived,function(value,name){var def=self._derived[name];def.deps=def.depList;var update=function(options){options=options||{};var newVal=def.fn.call(self);if(self._cache[name]!==newVal||!def.cache){if(def.cache){self._previousAttributes[name]=self._cache[name]}self._cache[name]=newVal;self.trigger("change:"+name,self,self._cache[name])}};def.deps.forEach(function(propString){self._keyTree.add(propString,update)})});this.on("all",function(eventName){if(changeRE.test(eventName)){self._keyTree.get(eventName.split(":")[1]).forEach(function(fn){fn()})}},this)},_getDerivedProperty:function(name,flushCache){if(this._derived[name].cache){if(flushCache||!this._cache.hasOwnProperty(name)){this._cache[name]=this._derived[name].fn.apply(this)}return this._cache[name]}else{return this._derived[name].fn.apply(this)}},_initCollections:function(){var coll;if(!this._collections)return;for(coll in this._collections){this[coll]=new this._collections[coll]([],{parent:this})}},_initChildren:function(){var child;if(!this._children)return;for(child in this._children){this[child]=new this._children[child]({},{parent:this});this.listenTo(this[child],"all",this._getEventBubblingHandler(child))}},_getEventBubblingHandler:function(propertyName){return _.bind(function(name,model,newValue){if(changeRE.test(name)){this.trigger("change:"+propertyName+"."+name.split(":")[1],model,newValue)}else if(name==="change"){this.trigger("change",this)}},this)},_verifyRequired:function(){var attrs=this.attributes;for(var def in this._definition){if(this._definition[def].required&&typeof attrs[def]==="undefined"){return false}}return true}});Object.defineProperties(Base.prototype,{attributes:{get:function(){return this.getAttributes({props:true,session:true})}},all:{get:function(){return this.getAttributes({session:true,props:true,derived:true})}},isState:{get:function(){return true},set:function(){}}});function createPropertyDefinition(object,name,desc,isSession){var def=object._definition[name]={};var type,descArray;if(_.isString(desc)){type=object._ensureValidType(desc);if(type)def.type=type}else{if(_.isArray(desc)){descArray=desc;desc={type:descArray[0],required:descArray[1],"default":descArray[2]}}type=object._ensureValidType(desc.type);if(type)def.type=type;if(desc.required)def.required=true;if(desc.default&&typeof desc.default==="object"){throw new TypeError("The default value for "+name+" cannot be an object/array, must be a value or a function which returns a value/object/array")}def.default=desc.default;def.allowNull=desc.allowNull?desc.allowNull:false;if(desc.setOnce)def.setOnce=true;if(def.required&&_.isUndefined(def.default))def.default=object._getDefaultForType(type);def.test=desc.test;def.values=desc.values}if(isSession)def.session=true;Object.defineProperty(object,name,{set:function(val){this.set(name,val)},get:function(){var result=this._values[name];var typeDef=this._dataTypes[def.type];if(typeof result!=="undefined"){if(typeDef&&typeDef.get){result=typeDef.get(result)}return result}return _.result(def,"default")}});return def}function createDerivedProperty(modelProto,name,definition){var def=modelProto._derived[name]={fn:_.isFunction(definition)?definition:definition.fn,cache:definition.cache!==false,depList:definition.deps||[]};_.each(def.depList,function(dep){modelProto._deps[dep]=_(modelProto._deps[dep]||[]).union([name])});Object.defineProperty(modelProto,name,{get:function(){return this._getDerivedProperty(name)},set:function(){throw new TypeError('"'+name+"\" is a derived property, it can't be set directly.")}})}var dataTypes={string:{"default":function(){return""}},date:{set:function(newVal){var newType;if(!_.isDate(newVal)){try{newVal=new Date(parseInt(newVal,10));if(!_.isDate(newVal))throw TypeError;newVal=newVal.valueOf();if(_.isNaN(newVal))throw TypeError;newType="date"}catch(e){newType=typeof newVal}}else{newType="date";newVal=newVal.valueOf()}return{val:newVal,type:newType}},get:function(val){return new Date(val)},"default":function(){return new Date}},array:{set:function(newVal){return{val:newVal,type:_.isArray(newVal)?"array":typeof newVal}},"default":function(){return[]}},object:{set:function(newVal){var newType=typeof newVal;if(newType!=="object"&&_.isUndefined(newVal)){newVal=null;newType="object"}return{val:newVal,type:newType}},"default":function(){return{}}},state:{set:function(newVal){var isInstance=newVal instanceof Base||newVal&&newVal.isState;if(isInstance){return{val:newVal,type:"state"}}else{return{val:newVal,type:typeof newVal}}},compare:function(currentVal,newVal,attributeName){var isSame=currentVal===newVal;if(!isSame){if(currentVal){this.stopListening(currentVal)}if(newVal!=null){this.listenTo(newVal,"all",this._getEventBubblingHandler(attributeName))}}return isSame}}};function extend(protoProps){var parent=this;var child;var args=[].slice.call(arguments);var prop,item;if(protoProps&&protoProps.hasOwnProperty("constructor")){child=protoProps.constructor}else{child=function(){return parent.apply(this,arguments)}}_.extend(child,parent);var Surrogate=function(){this.constructor=child};Surrogate.prototype=parent.prototype;child.prototype=new Surrogate;child.prototype._derived=_.extend({},parent.prototype._derived);child.prototype._deps=_.extend({},parent.prototype._deps);child.prototype._definition=_.extend({},parent.prototype._definition);child.prototype._collections=_.extend({},parent.prototype._collections);child.prototype._children=_.extend({},parent.prototype._children);child.prototype._dataTypes=_.extend({},parent.prototype._dataTypes||dataTypes);if(protoProps){args.forEach(function processArg(def){if(def.dataTypes){_.each(def.dataTypes,function(def,name){child.prototype._dataTypes[name]=def});delete def.dataTypes}if(def.props){_.each(def.props,function(def,name){createPropertyDefinition(child.prototype,name,def)});delete def.props}if(def.session){_.each(def.session,function(def,name){createPropertyDefinition(child.prototype,name,def,true)});delete def.session}if(def.derived){_.each(def.derived,function(def,name){createDerivedProperty(child.prototype,name,def)});delete def.derived}if(def.collections){_.each(def.collections,function(constructor,name){child.prototype._collections[name]=constructor});delete def.collections}if(def.children){_.each(def.children,function(constructor,name){child.prototype._children[name]=constructor});delete def.children}_.extend(child.prototype,def)})}var toString=Object.prototype.toString;child.__super__=parent.prototype;return child}Base.extend=extend;module.exports=Base},{"array-next":11,"backbone-events-standalone":13,"key-tree-store":14,underscore:23}],11:[function(require,module,exports){module.exports=function arrayNext(array,currentItem){var len=array.length;var newIndex=array.indexOf(currentItem)+1;if(newIndex>len-1)newIndex=0;return array[newIndex]}},{}],12:[function(require,module,exports){(function(){var root=this,breaker={},nativeForEach=Array.prototype.forEach,hasOwnProperty=Object.prototype.hasOwnProperty,slice=Array.prototype.slice,idCounter=0;function miniscore(){return{keys:Object.keys,uniqueId:function(prefix){var id=++idCounter+"";return prefix?prefix+id:id},has:function(obj,key){return hasOwnProperty.call(obj,key)},each:function(obj,iterator,context){if(obj==null)return;if(nativeForEach&&obj.forEach===nativeForEach){obj.forEach(iterator,context)}else if(obj.length===+obj.length){for(var i=0,l=obj.length;i<l;i++){if(iterator.call(context,obj[i],i,obj)===breaker)return}}else{for(var key in obj){if(this.has(obj,key)){if(iterator.call(context,obj[key],key,obj)===breaker)return}}}},once:function(func){var ran=false,memo;
return function(){if(ran)return memo;ran=true;memo=func.apply(this,arguments);func=null;return memo}}}}var _=miniscore(),Events;Events={on:function(name,callback,context){if(!eventsApi(this,"on",name,[callback,context])||!callback)return this;this._events||(this._events={});var events=this._events[name]||(this._events[name]=[]);events.push({callback:callback,context:context,ctx:context||this});return this},once:function(name,callback,context){if(!eventsApi(this,"once",name,[callback,context])||!callback)return this;var self=this;var once=_.once(function(){self.off(name,once);callback.apply(this,arguments)});once._callback=callback;return this.on(name,once,context)},off:function(name,callback,context){var retain,ev,events,names,i,l,j,k;if(!this._events||!eventsApi(this,"off",name,[callback,context]))return this;if(!name&&!callback&&!context){this._events={};return this}names=name?[name]:_.keys(this._events);for(i=0,l=names.length;i<l;i++){name=names[i];if(events=this._events[name]){this._events[name]=retain=[];if(callback||context){for(j=0,k=events.length;j<k;j++){ev=events[j];if(callback&&callback!==ev.callback&&callback!==ev.callback._callback||context&&context!==ev.context){retain.push(ev)}}}if(!retain.length)delete this._events[name]}}return this},trigger:function(name){if(!this._events)return this;var args=slice.call(arguments,1);if(!eventsApi(this,"trigger",name,args))return this;var events=this._events[name];var allEvents=this._events.all;if(events)triggerEvents(events,args);if(allEvents)triggerEvents(allEvents,arguments);return this},stopListening:function(obj,name,callback){var listeners=this._listeners;if(!listeners)return this;var deleteListener=!name&&!callback;if(typeof name==="object")callback=this;if(obj)(listeners={})[obj._listenerId]=obj;for(var id in listeners){listeners[id].off(name,callback,this);if(deleteListener)delete this._listeners[id]}return this}};var eventSplitter=/\s+/;var eventsApi=function(obj,action,name,rest){if(!name)return true;if(typeof name==="object"){for(var key in name){obj[action].apply(obj,[key,name[key]].concat(rest))}return false}if(eventSplitter.test(name)){var names=name.split(eventSplitter);for(var i=0,l=names.length;i<l;i++){obj[action].apply(obj,[names[i]].concat(rest))}return false}return true};var triggerEvents=function(events,args){var ev,i=-1,l=events.length,a1=args[0],a2=args[1],a3=args[2];switch(args.length){case 0:while(++i<l)(ev=events[i]).callback.call(ev.ctx);return;case 1:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1);return;case 2:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2);return;case 3:while(++i<l)(ev=events[i]).callback.call(ev.ctx,a1,a2,a3);return;default:while(++i<l)(ev=events[i]).callback.apply(ev.ctx,args)}};var listenMethods={listenTo:"on",listenToOnce:"once"};_.each(listenMethods,function(implementation,method){Events[method]=function(obj,name,callback){var listeners=this._listeners||(this._listeners={});var id=obj._listenerId||(obj._listenerId=_.uniqueId("l"));listeners[id]=obj;if(typeof name==="object")callback=this;obj[implementation](name,callback,this);return this}});Events.bind=Events.on;Events.unbind=Events.off;Events.mixin=function(proto){var exports=["on","once","off","trigger","stopListening","listenTo","listenToOnce","bind","unbind"];_.each(exports,function(name){proto[name]=this[name]},this);return proto};if(typeof define==="function"){define(function(){return Events})}else if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){exports=module.exports=Events}exports.BackboneEvents=Events}else{root.BackboneEvents=Events}})(this)},{}],13:[function(require,module,exports){arguments[4][5][0].apply(exports,arguments)},{"./backbone-events-standalone":12}],14:[function(require,module,exports){function KeyTreeStore(){this.storage={}}KeyTreeStore.prototype.add=function(keypath,obj){var arr=this.storage[keypath]||(this.storage[keypath]=[]);arr.push(obj)};KeyTreeStore.prototype.remove=function(obj){var path,arr;for(path in this.storage){arr=this.storage[path];arr.some(function(item,index){if(item===obj){arr.splice(index,1);return true}})}};KeyTreeStore.prototype.get=function(keypath){var res=[];var key;for(key in this.storage){if(keypath===key||key.indexOf(keypath+".")===0){res=res.concat(this.storage[key])}}return res};module.exports=KeyTreeStore},{}],15:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],16:[function(require,module,exports){var events=require("component-event");var delegate=require("delegate-events");var forceCaptureEvents=["focus","blur"];module.exports=Events;function Events(el,obj){if(!(this instanceof Events))return new Events(el,obj);if(!el)throw new Error("element required");if(!obj)throw new Error("object required");this.el=el;this.obj=obj;this._events={}}Events.prototype.sub=function(event,method,cb){this._events[event]=this._events[event]||{};this._events[event][method]=cb};Events.prototype.bind=function(event,method){var e=parse(event);var el=this.el;var obj=this.obj;var name=e.name;var method=method||"on"+name;var args=[].slice.call(arguments,2);function cb(){var a=[].slice.call(arguments).concat(args);obj[method].apply(obj,a)}if(e.selector){cb=delegate.bind(el,e.selector,name,cb)}else{events.bind(el,name,cb)}this.sub(name,method,cb);return cb};Events.prototype.unbind=function(event,method){if(0==arguments.length)return this.unbindAll();if(1==arguments.length)return this.unbindAllOf(event);var bindings=this._events[event];var capture=forceCaptureEvents.indexOf(event)!==-1;if(!bindings)return;var cb=bindings[method];if(!cb)return;events.unbind(this.el,event,cb,capture)};Events.prototype.unbindAll=function(){for(var event in this._events){this.unbindAllOf(event)}};Events.prototype.unbindAllOf=function(event){var bindings=this._events[event];if(!bindings)return;for(var method in bindings){this.unbind(event,method)}};function parse(event){var parts=event.split(/ +/);return{name:parts.shift(),selector:parts.join(" ")}}},{"component-event":17,"delegate-events":18}],17:[function(require,module,exports){var bind=window.addEventListener?"addEventListener":"attachEvent",unbind=window.removeEventListener?"removeEventListener":"detachEvent",prefix=bind!=="addEventListener"?"on":"";exports.bind=function(el,type,fn,capture){el[bind](prefix+type,fn,capture||false);return fn};exports.unbind=function(el,type,fn,capture){el[unbind](prefix+type,fn,capture||false);return fn}},{}],18:[function(require,module,exports){var closest=require("closest"),event=require("event");var forceCaptureEvents=["focus","blur"];exports.bind=function(el,selector,type,fn,capture){if(forceCaptureEvents.indexOf(type)!==-1)capture=true;return event.bind(el,type,function(e){var target=e.target||e.srcElement;e.delegateTarget=closest(target,selector,true,el);if(e.delegateTarget)fn.call(el,e)},capture)};exports.unbind=function(el,type,fn,capture){if(forceCaptureEvents.indexOf(type)!==-1)capture=true;event.unbind(el,type,fn,capture)}},{closest:19,event:17}],19:[function(require,module,exports){var matches=require("matches-selector");module.exports=function(element,selector,checkYoSelf){var parent=checkYoSelf?element:element.parentNode;while(parent&&parent!==document){if(matches(parent,selector))return parent;parent=parent.parentNode}}},{"matches-selector":20}],20:[function(require,module,exports){var proto=Element.prototype;var vendor=proto.matchesSelector||proto.webkitMatchesSelector||proto.mozMatchesSelector||proto.msMatchesSelector||proto.oMatchesSelector;module.exports=match;function match(el,selector){if(vendor)return vendor.call(el,selector);var nodes=el.parentNode.querySelectorAll(selector);for(var i=0;i<nodes.length;++i){if(nodes[i]==el)return true}return false}},{}],21:[function(require,module,exports){module.exports=get;function get(context,path){if(path.indexOf(".")==-1&&path.indexOf("[")==-1){return context[path]}var crumbs=path.split(/\.|\[|\]/g);var i=-1;var len=crumbs.length;var result;while(++i<len){if(i==0)result=context;if(!crumbs[i])continue;if(result==undefined)break;result=result[crumbs[i]]}return result}},{}],22:[function(require,module,exports){"use strict";var proto=Element.prototype;var vendor=proto.matches||proto.matchesSelector||proto.webkitMatchesSelector||proto.mozMatchesSelector||proto.msMatchesSelector||proto.oMatchesSelector;module.exports=match;function match(el,selector){if(vendor)return vendor.call(el,selector);var nodes=el.parentNode.querySelectorAll(selector);for(var i=0;i<nodes.length;i++){if(nodes[i]==el)return true}return false}},{}],23:[function(require,module,exports){(function(){var root=this;var previousUnderscore=root._;var breaker={};var ArrayProto=Array.prototype,ObjProto=Object.prototype,FuncProto=Function.prototype;var push=ArrayProto.push,slice=ArrayProto.slice,concat=ArrayProto.concat,toString=ObjProto.toString,hasOwnProperty=ObjProto.hasOwnProperty;var nativeForEach=ArrayProto.forEach,nativeMap=ArrayProto.map,nativeReduce=ArrayProto.reduce,nativeReduceRight=ArrayProto.reduceRight,nativeFilter=ArrayProto.filter,nativeEvery=ArrayProto.every,nativeSome=ArrayProto.some,nativeIndexOf=ArrayProto.indexOf,nativeLastIndexOf=ArrayProto.lastIndexOf,nativeIsArray=Array.isArray,nativeKeys=Object.keys,nativeBind=FuncProto.bind;var _=function(obj){if(obj instanceof _)return obj;if(!(this instanceof _))return new _(obj);this._wrapped=obj};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){exports=module.exports=_}exports._=_}else{root._=_}_.VERSION="1.6.0";var each=_.each=_.forEach=function(obj,iterator,context){if(obj==null)return obj;if(nativeForEach&&obj.forEach===nativeForEach){obj.forEach(iterator,context)}else if(obj.length===+obj.length){for(var i=0,length=obj.length;i<length;i++){if(iterator.call(context,obj[i],i,obj)===breaker)return}}else{var keys=_.keys(obj);for(var i=0,length=keys.length;i<length;i++){if(iterator.call(context,obj[keys[i]],keys[i],obj)===breaker)return}}return obj};_.map=_.collect=function(obj,iterator,context){var results=[];if(obj==null)return results;if(nativeMap&&obj.map===nativeMap)return obj.map(iterator,context);each(obj,function(value,index,list){results.push(iterator.call(context,value,index,list))});return results};var reduceError="Reduce of empty array with no initial value";_.reduce=_.foldl=_.inject=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduce&&obj.reduce===nativeReduce){if(context)iterator=_.bind(iterator,context);return initial?obj.reduce(iterator,memo):obj.reduce(iterator)}each(obj,function(value,index,list){if(!initial){memo=value;initial=true}else{memo=iterator.call(context,memo,value,index,list)}});if(!initial)throw new TypeError(reduceError);return memo};_.reduceRight=_.foldr=function(obj,iterator,memo,context){var initial=arguments.length>2;if(obj==null)obj=[];if(nativeReduceRight&&obj.reduceRight===nativeReduceRight){if(context)iterator=_.bind(iterator,context);return initial?obj.reduceRight(iterator,memo):obj.reduceRight(iterator)}var length=obj.length;if(length!==+length){var keys=_.keys(obj);length=keys.length}each(obj,function(value,index,list){index=keys?keys[--length]:--length;if(!initial){memo=obj[index];initial=true}else{memo=iterator.call(context,memo,obj[index],index,list)}});if(!initial)throw new TypeError(reduceError);return memo};_.find=_.detect=function(obj,predicate,context){var result;any(obj,function(value,index,list){if(predicate.call(context,value,index,list)){result=value;return true}});return result};_.filter=_.select=function(obj,predicate,context){var results=[];if(obj==null)return results;if(nativeFilter&&obj.filter===nativeFilter)return obj.filter(predicate,context);each(obj,function(value,index,list){if(predicate.call(context,value,index,list))results.push(value)});return results};_.reject=function(obj,predicate,context){return _.filter(obj,function(value,index,list){return!predicate.call(context,value,index,list)},context)};_.every=_.all=function(obj,predicate,context){predicate||(predicate=_.identity);var result=true;if(obj==null)return result;if(nativeEvery&&obj.every===nativeEvery)return obj.every(predicate,context);each(obj,function(value,index,list){if(!(result=result&&predicate.call(context,value,index,list)))return breaker});return!!result};var any=_.some=_.any=function(obj,predicate,context){predicate||(predicate=_.identity);var result=false;if(obj==null)return result;if(nativeSome&&obj.some===nativeSome)return obj.some(predicate,context);each(obj,function(value,index,list){if(result||(result=predicate.call(context,value,index,list)))return breaker});return!!result};_.contains=_.include=function(obj,target){if(obj==null)return false;if(nativeIndexOf&&obj.indexOf===nativeIndexOf)return obj.indexOf(target)!=-1;return any(obj,function(value){return value===target})};_.invoke=function(obj,method){var args=slice.call(arguments,2);var isFunc=_.isFunction(method);return _.map(obj,function(value){return(isFunc?method:value[method]).apply(value,args)})};_.pluck=function(obj,key){return _.map(obj,_.property(key))};_.where=function(obj,attrs){return _.filter(obj,_.matches(attrs))};_.findWhere=function(obj,attrs){return _.find(obj,_.matches(attrs))};_.max=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.max.apply(Math,obj)}var result=-Infinity,lastComputed=-Infinity;each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;if(computed>lastComputed){result=value;lastComputed=computed}});return result};_.min=function(obj,iterator,context){if(!iterator&&_.isArray(obj)&&obj[0]===+obj[0]&&obj.length<65535){return Math.min.apply(Math,obj)}var result=Infinity,lastComputed=Infinity;each(obj,function(value,index,list){var computed=iterator?iterator.call(context,value,index,list):value;if(computed<lastComputed){result=value;lastComputed=computed}});return result};_.shuffle=function(obj){var rand;var index=0;var shuffled=[];each(obj,function(value){rand=_.random(index++);shuffled[index-1]=shuffled[rand];shuffled[rand]=value});return shuffled};_.sample=function(obj,n,guard){if(n==null||guard){if(obj.length!==+obj.length)obj=_.values(obj);return obj[_.random(obj.length-1)]}return _.shuffle(obj).slice(0,Math.max(0,n))};var lookupIterator=function(value){if(value==null)return _.identity;if(_.isFunction(value))return value;return _.property(value)};_.sortBy=function(obj,iterator,context){iterator=lookupIterator(iterator);return _.pluck(_.map(obj,function(value,index,list){return{value:value,index:index,criteria:iterator.call(context,value,index,list)}}).sort(function(left,right){var a=left.criteria;var b=right.criteria;if(a!==b){if(a>b||a===void 0)return 1;if(a<b||b===void 0)return-1}return left.index-right.index}),"value")};var group=function(behavior){return function(obj,iterator,context){var result={};iterator=lookupIterator(iterator);each(obj,function(value,index){var key=iterator.call(context,value,index,obj);behavior(result,key,value)});return result}};_.groupBy=group(function(result,key,value){_.has(result,key)?result[key].push(value):result[key]=[value]});_.indexBy=group(function(result,key,value){result[key]=value});_.countBy=group(function(result,key){_.has(result,key)?result[key]++:result[key]=1});_.sortedIndex=function(array,obj,iterator,context){iterator=lookupIterator(iterator);var value=iterator.call(context,obj);var low=0,high=array.length;while(low<high){var mid=low+high>>>1;iterator.call(context,array[mid])<value?low=mid+1:high=mid}return low};_.toArray=function(obj){if(!obj)return[];if(_.isArray(obj))return slice.call(obj);if(obj.length===+obj.length)return _.map(obj,_.identity);return _.values(obj)};_.size=function(obj){if(obj==null)return 0;return obj.length===+obj.length?obj.length:_.keys(obj).length};_.first=_.head=_.take=function(array,n,guard){if(array==null)return void 0;if(n==null||guard)return array[0];if(n<0)return[];return slice.call(array,0,n)};_.initial=function(array,n,guard){return slice.call(array,0,array.length-(n==null||guard?1:n))};_.last=function(array,n,guard){if(array==null)return void 0;if(n==null||guard)return array[array.length-1];return slice.call(array,Math.max(array.length-n,0))};_.rest=_.tail=_.drop=function(array,n,guard){return slice.call(array,n==null||guard?1:n)};_.compact=function(array){return _.filter(array,_.identity)};var flatten=function(input,shallow,output){if(shallow&&_.every(input,_.isArray)){return concat.apply(output,input)}each(input,function(value){if(_.isArray(value)||_.isArguments(value)){shallow?push.apply(output,value):flatten(value,shallow,output)}else{output.push(value)}});return output};_.flatten=function(array,shallow){return flatten(array,shallow,[])};_.without=function(array){return _.difference(array,slice.call(arguments,1))};_.partition=function(array,predicate){var pass=[],fail=[];each(array,function(elem){(predicate(elem)?pass:fail).push(elem)});return[pass,fail]};_.uniq=_.unique=function(array,isSorted,iterator,context){if(_.isFunction(isSorted)){context=iterator;iterator=isSorted;isSorted=false}var initial=iterator?_.map(array,iterator,context):array;var results=[];var seen=[];each(initial,function(value,index){if(isSorted?!index||seen[seen.length-1]!==value:!_.contains(seen,value)){seen.push(value);results.push(array[index])}});return results};_.union=function(){return _.uniq(_.flatten(arguments,true))};_.intersection=function(array){var rest=slice.call(arguments,1);return _.filter(_.uniq(array),function(item){return _.every(rest,function(other){return _.contains(other,item)})})};_.difference=function(array){var rest=concat.apply(ArrayProto,slice.call(arguments,1));return _.filter(array,function(value){return!_.contains(rest,value)})};_.zip=function(){var length=_.max(_.pluck(arguments,"length").concat(0));var results=new Array(length);for(var i=0;i<length;i++){results[i]=_.pluck(arguments,""+i)}return results};_.object=function(list,values){if(list==null)return{};var result={};for(var i=0,length=list.length;i<length;i++){if(values){result[list[i]]=values[i]}else{result[list[i][0]]=list[i][1]}}return result};_.indexOf=function(array,item,isSorted){if(array==null)return-1;var i=0,length=array.length;if(isSorted){if(typeof isSorted=="number"){i=isSorted<0?Math.max(0,length+isSorted):isSorted}else{i=_.sortedIndex(array,item);return array[i]===item?i:-1}}if(nativeIndexOf&&array.indexOf===nativeIndexOf)return array.indexOf(item,isSorted);for(;i<length;i++)if(array[i]===item)return i;return-1};_.lastIndexOf=function(array,item,from){if(array==null)return-1;var hasIndex=from!=null;if(nativeLastIndexOf&&array.lastIndexOf===nativeLastIndexOf){return hasIndex?array.lastIndexOf(item,from):array.lastIndexOf(item)}var i=hasIndex?from:array.length;while(i--)if(array[i]===item)return i;return-1};_.range=function(start,stop,step){if(arguments.length<=1){stop=start||0;start=0}step=arguments[2]||1;var length=Math.max(Math.ceil((stop-start)/step),0);var idx=0;var range=new Array(length);while(idx<length){range[idx++]=start;start+=step}return range};var ctor=function(){};_.bind=function(func,context){var args,bound;if(nativeBind&&func.bind===nativeBind)return nativeBind.apply(func,slice.call(arguments,1));if(!_.isFunction(func))throw new TypeError;args=slice.call(arguments,2);return bound=function(){if(!(this instanceof bound))return func.apply(context,args.concat(slice.call(arguments)));ctor.prototype=func.prototype;var self=new ctor;ctor.prototype=null;var result=func.apply(self,args.concat(slice.call(arguments)));if(Object(result)===result)return result;return self}};_.partial=function(func){var boundArgs=slice.call(arguments,1);return function(){var position=0;var args=boundArgs.slice();for(var i=0,length=args.length;i<length;i++){if(args[i]===_)args[i]=arguments[position++]}while(position<arguments.length)args.push(arguments[position++]);return func.apply(this,args)}};_.bindAll=function(obj){var funcs=slice.call(arguments,1);if(funcs.length===0)throw new Error("bindAll must be passed function names");each(funcs,function(f){obj[f]=_.bind(obj[f],obj)});return obj};_.memoize=function(func,hasher){var memo={};hasher||(hasher=_.identity);return function(){var key=hasher.apply(this,arguments);return _.has(memo,key)?memo[key]:memo[key]=func.apply(this,arguments)}};_.delay=function(func,wait){var args=slice.call(arguments,2);return setTimeout(function(){return func.apply(null,args)},wait)};_.defer=function(func){return _.delay.apply(_,[func,1].concat(slice.call(arguments,1)))};_.throttle=function(func,wait,options){var context,args,result;var timeout=null;var previous=0;options||(options={});var later=function(){previous=options.leading===false?0:_.now();timeout=null;result=func.apply(context,args);context=args=null};return function(){var now=_.now();if(!previous&&options.leading===false)previous=now;var remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0){clearTimeout(timeout);timeout=null;previous=now;result=func.apply(context,args);context=args=null}else if(!timeout&&options.trailing!==false){timeout=setTimeout(later,remaining)}return result}};_.debounce=function(func,wait,immediate){var timeout,args,context,timestamp,result;var later=function(){var last=_.now()-timestamp;if(last<wait){timeout=setTimeout(later,wait-last)}else{timeout=null;if(!immediate){result=func.apply(context,args);context=args=null}}};return function(){context=this;args=arguments;timestamp=_.now();var callNow=immediate&&!timeout;if(!timeout){timeout=setTimeout(later,wait)}if(callNow){result=func.apply(context,args);context=args=null}return result}};_.once=function(func){var ran=false,memo;return function(){if(ran)return memo;ran=true;memo=func.apply(this,arguments);func=null;return memo}};_.wrap=function(func,wrapper){return _.partial(wrapper,func)};_.compose=function(){var funcs=arguments;return function(){var args=arguments;for(var i=funcs.length-1;i>=0;i--){args=[funcs[i].apply(this,args)]}return args[0]}};_.after=function(times,func){return function(){if(--times<1){return func.apply(this,arguments)}}};_.keys=function(obj){if(!_.isObject(obj))return[];if(nativeKeys)return nativeKeys(obj);var keys=[];for(var key in obj)if(_.has(obj,key))keys.push(key);return keys};_.values=function(obj){var keys=_.keys(obj);var length=keys.length;var values=new Array(length);for(var i=0;i<length;i++){values[i]=obj[keys[i]]}return values};_.pairs=function(obj){var keys=_.keys(obj);var length=keys.length;var pairs=new Array(length);for(var i=0;i<length;i++){pairs[i]=[keys[i],obj[keys[i]]]}return pairs};_.invert=function(obj){var result={};var keys=_.keys(obj);for(var i=0,length=keys.length;i<length;i++){result[obj[keys[i]]]=keys[i]}return result};_.functions=_.methods=function(obj){var names=[];for(var key in obj){if(_.isFunction(obj[key]))names.push(key)}return names.sort()};_.extend=function(obj){each(slice.call(arguments,1),function(source){if(source){for(var prop in source){obj[prop]=source[prop]}}});return obj};_.pick=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));each(keys,function(key){if(key in obj)copy[key]=obj[key]});return copy};_.omit=function(obj){var copy={};var keys=concat.apply(ArrayProto,slice.call(arguments,1));for(var key in obj){if(!_.contains(keys,key))copy[key]=obj[key]}return copy};_.defaults=function(obj){each(slice.call(arguments,1),function(source){if(source){for(var prop in source){if(obj[prop]===void 0)obj[prop]=source[prop]}}});return obj};_.clone=function(obj){if(!_.isObject(obj))return obj;return _.isArray(obj)?obj.slice():_.extend({},obj)};_.tap=function(obj,interceptor){interceptor(obj);return obj};var eq=function(a,b,aStack,bStack){if(a===b)return a!==0||1/a==1/b;if(a==null||b==null)return a===b;if(a instanceof _)a=a._wrapped;if(b instanceof _)b=b._wrapped;var className=toString.call(a);if(className!=toString.call(b))return false;switch(className){case"[object String]":return a==String(b);case"[object Number]":return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case"[object Date]":case"[object Boolean]":return+a==+b;case"[object RegExp]":return a.source==b.source&&a.global==b.global&&a.multiline==b.multiline&&a.ignoreCase==b.ignoreCase}if(typeof a!="object"||typeof b!="object")return false;var length=aStack.length;while(length--){if(aStack[length]==a)return bStack[length]==b}var aCtor=a.constructor,bCtor=b.constructor;if(aCtor!==bCtor&&!(_.isFunction(aCtor)&&aCtor instanceof aCtor&&_.isFunction(bCtor)&&bCtor instanceof bCtor)&&("constructor"in a&&"constructor"in b)){return false}aStack.push(a);bStack.push(b);var size=0,result=true;if(className=="[object Array]"){size=a.length;result=size==b.length;if(result){while(size--){if(!(result=eq(a[size],b[size],aStack,bStack)))break}}}else{for(var key in a){if(_.has(a,key)){size++;if(!(result=_.has(b,key)&&eq(a[key],b[key],aStack,bStack)))break}}if(result){for(key in b){if(_.has(b,key)&&!size--)break}result=!size}}aStack.pop();bStack.pop();return result};_.isEqual=function(a,b){return eq(a,b,[],[])};_.isEmpty=function(obj){if(obj==null)return true;if(_.isArray(obj)||_.isString(obj))return obj.length===0;for(var key in obj)if(_.has(obj,key))return false;return true};_.isElement=function(obj){return!!(obj&&obj.nodeType===1)};_.isArray=nativeIsArray||function(obj){return toString.call(obj)=="[object Array]"};_.isObject=function(obj){return obj===Object(obj)};each(["Arguments","Function","String","Number","Date","RegExp"],function(name){_["is"+name]=function(obj){return toString.call(obj)=="[object "+name+"]"}});if(!_.isArguments(arguments)){_.isArguments=function(obj){return!!(obj&&_.has(obj,"callee"))}}if(typeof/./!=="function"){_.isFunction=function(obj){return typeof obj==="function"}}_.isFinite=function(obj){return isFinite(obj)&&!isNaN(parseFloat(obj))};_.isNaN=function(obj){return _.isNumber(obj)&&obj!=+obj};_.isBoolean=function(obj){return obj===true||obj===false||toString.call(obj)=="[object Boolean]"};_.isNull=function(obj){return obj===null};_.isUndefined=function(obj){return obj===void 0};_.has=function(obj,key){return hasOwnProperty.call(obj,key)};_.noConflict=function(){root._=previousUnderscore;return this};_.identity=function(value){return value};_.constant=function(value){return function(){return value}};_.property=function(key){return function(obj){return obj[key]}};_.matches=function(attrs){return function(obj){if(obj===attrs)return true;for(var key in attrs){if(attrs[key]!==obj[key])return false}return true}};_.times=function(n,iterator,context){var accum=Array(Math.max(0,n));for(var i=0;i<n;i++)accum[i]=iterator.call(context,i);return accum};_.random=function(min,max){if(max==null){max=min;min=0}return min+Math.floor(Math.random()*(max-min+1))};_.now=Date.now||function(){return(new Date).getTime()};var entityMap={escape:{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"}};entityMap.unescape=_.invert(entityMap.escape);var entityRegexes={escape:new RegExp("["+_.keys(entityMap.escape).join("")+"]","g"),unescape:new RegExp("("+_.keys(entityMap.unescape).join("|")+")","g")};_.each(["escape","unescape"],function(method){_[method]=function(string){if(string==null)return"";return(""+string).replace(entityRegexes[method],function(match){return entityMap[method][match]})}});_.result=function(object,property){if(object==null)return void 0;var value=object[property];return _.isFunction(value)?value.call(object):value};_.mixin=function(obj){each(_.functions(obj),function(name){var func=_[name]=obj[name];_.prototype[name]=function(){var args=[this._wrapped];push.apply(args,arguments);return result.call(this,func.apply(_,args))}})};var idCounter=0;_.uniqueId=function(prefix){var id=++idCounter+"";return prefix?prefix+id:id};_.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var noMatch=/(.)^/;var escapes={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"};var escaper=/\\|'|\r|\n|\t|\u2028|\u2029/g;_.template=function(text,data,settings){var render;settings=_.defaults({},settings,_.templateSettings);var matcher=new RegExp([(settings.escape||noMatch).source,(settings.interpolate||noMatch).source,(settings.evaluate||noMatch).source].join("|")+"|$","g");var index=0;var source="__p+='";text.replace(matcher,function(match,escape,interpolate,evaluate,offset){source+=text.slice(index,offset).replace(escaper,function(match){return"\\"+escapes[match]});if(escape){source+="'+\n((__t=("+escape+"))==null?'':_.escape(__t))+\n'"}if(interpolate){source+="'+\n((__t=("+interpolate+"))==null?'':__t)+\n'"}if(evaluate){source+="';\n"+evaluate+"\n__p+='"}index=offset+match.length;return match});source+="';\n";if(!settings.variable)source="with(obj||{}){\n"+source+"}\n";source="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+source+"return __p;\n";try{render=new Function(settings.variable||"obj","_",source)}catch(e){e.source=source;throw e}if(data)return render(data,_);var template=function(data){return render.call(this,data,_)};template.source="function("+(settings.variable||"obj")+"){\n"+source+"}";return template};_.chain=function(obj){return _(obj).chain()};var result=function(obj){return this._chain?_(obj).chain():obj};_.mixin(_);each(["pop","push","reverse","shift","sort","splice","unshift"],function(name){var method=ArrayProto[name];_.prototype[name]=function(){var obj=this._wrapped;method.apply(obj,arguments);if((name=="shift"||name=="splice")&&obj.length===0)delete obj[0];return result.call(this,obj)}});each(["concat","join","slice"],function(name){var method=ArrayProto[name];_.prototype[name]=function(){return result.call(this,method.apply(this._wrapped,arguments))}});_.extend(_.prototype,{chain:function(){this._chain=true;return this},value:function(){return this._wrapped}});if(typeof define==="function"&&define.amd){define("underscore",[],function(){return _})}}).call(this)},{}],"ampersand-view":[function(require,module,exports){var State=require("ampersand-state");var CollectionView=require("ampersand-collection-view");var domify=require("domify");var _=require("underscore");var events=require("events-mixin");var matches=require("matches-selector");var bindings=require("ampersand-dom-bindings");var getPath=require("get-object-path");function View(attrs){this.cid=_.uniqueId("view");attrs||(attrs={});var parent=attrs.parent;delete attrs.parent;BaseState.call(this,attrs,{init:false,parent:parent});this.on("change:el",this._handleElementChange,this);this._parsedBindings=bindings(this.bindings);
this._initializeBindings();if(attrs.el&&!this.autoRender){this._handleElementChange()}this._initializeSubviews();this.initialize.apply(this,arguments);this.set(_.pick(attrs,viewOptions));if(this.autoRender&&this.template){this.render()}}var BaseState=State.extend({dataTypes:{element:{set:function(newVal){return{val:newVal,type:newVal instanceof Element?"element":typeof newVal}},compare:function(el1,el2){return el1===el2}},collection:{set:function(newVal){return{val:newVal,type:newVal&&newVal.isCollection?"collection":typeof newVal}},compare:function(currentVal,newVal){return currentVal===newVal}}},props:{model:"state",el:"element",collection:"collection"},derived:{rendered:{deps:["el"],fn:function(){return!!this.el}},hasData:{deps:["model"],fn:function(){return!!this.model}}}});var delegateEventSplitter=/^(\S+)\s*(.*)$/;var viewOptions=["model","collection","el"];View.prototype=Object.create(BaseState.prototype);_.extend(View.prototype,{query:function(selector){if(!selector)return this.el;if(typeof selector==="string"){if(matches(this.el,selector))return this.el;return this.el.querySelector(selector)||undefined}return selector},queryAll:function(selector){var res=[];if(!this.el)return res;if(selector==="")return[this.el];if(matches(this.el,selector))res.push(this.el);return res.concat(Array.prototype.slice.call(this.el.querySelectorAll(selector)))},queryByHook:function(hook){return this.query('[data-hook~="'+hook+'"]')},initialize:function(){},render:function(){this.renderWithTemplate(this);return this},remove:function(){var parsedBindings=this._parsedBindings;if(this.el&&this.el.parentNode)this.el.parentNode.removeChild(this.el);if(this._subviews)_.chain(this._subviews).flatten().invoke("remove");this.stopListening();_.each(parsedBindings,function(properties,modelName){_.each(properties,function(value,key){delete parsedBindings[modelName][key]});delete parsedBindings[modelName]});this.trigger("remove",this);return this},_handleElementChange:function(element,delegate){if(this.eventManager)this.eventManager.unbind();this.eventManager=events(this.el,this);this.delegateEvents();this._applyBindingsForKey();return this},delegateEvents:function(events){if(!(events||(events=_.result(this,"events"))))return this;this.undelegateEvents();for(var key in events){this.eventManager.bind(key,events[key])}return this},undelegateEvents:function(){this.eventManager.unbind();return this},registerSubview:function(view){this._subviews||(this._subviews=[]);this._subviews.push(view);if(view.el)view.parent=this;return view},renderSubview:function(view,container){if(typeof container==="string"){container=this.query(container)}this.registerSubview(view);view.render();(container||this.el).appendChild(view.el);return view},_applyBindingsForKey:function(name){if(!this.el)return;var fns=this._parsedBindings.getGrouped(name);var item;for(item in fns){fns[item].forEach(function(fn){fn(this.el,getPath(this,item),_.last(item.split(".")))},this)}},_initializeBindings:function(){if(!this.bindings)return;this.on("all",function(eventName){if(eventName.slice(0,7)==="change:"){this._applyBindingsForKey(eventName.split(":")[1])}},this)},_initializeSubviews:function(){if(!this.subviews)return;for(var item in this.subviews){this._parseSubview(this.subviews[item],item)}},_parseSubview:function(subview,name){var self=this;var opts={selector:subview.container||'[data-hook="'+subview.hook+'"]',waitFor:subview.waitFor||"",prepareView:subview.prepareView||function(el){return new subview.constructor({el:el,parent:self})}};function action(){var el,subview;if(!this.el||!(el=this.query(opts.selector)))return;if(!opts.waitFor||getPath(this,opts.waitFor)){subview=this[name]=opts.prepareView.call(this,el);subview.render();this.registerSubview(subview);this.off("change",action)}}this.on("change",action,this)},renderWithTemplate:function(context,templateArg){var template=templateArg||this.template;if(!template)throw new Error("Template string or function needed.");var newDom=_.isString(template)?template:template(context||this);if(_.isString(newDom))newDom=domify(newDom);var parent=this.el&&this.el.parentNode;if(parent)parent.replaceChild(newDom,this.el);if(newDom.nodeName==="#document-fragment")throw new Error("Views can only have one root element.");this.el=newDom;return this},cacheElements:function(hash){for(var item in hash){this[item]=this.query(hash[item])}},listenToAndRun:function(object,events,handler){var bound=_.bind(handler,this);this.listenTo(object,events,bound);bound()},animateRemove:function(){this.remove()},renderCollection:function(collection,ViewClass,container,opts){var containerEl=typeof container==="string"?this.query(container):container;var config=_.extend({collection:collection,el:containerEl||this.el,view:ViewClass,parent:this,viewOptions:{parent:this}},opts);var collectionView=new CollectionView(config);collectionView.render();return this.registerSubview(collectionView)}});View.extend=BaseState.extend;module.exports=View},{"ampersand-collection-view":1,"ampersand-dom-bindings":6,"ampersand-state":10,domify:15,"events-mixin":16,"get-object-path":21,"matches-selector":22,underscore:23}]},{},[]);var View=require("ampersand-view"),domReady=require("domready");var MyView=View.extend({el:document.body,template:"<div><div data-hook='last-clicked'></div><a data-hook='test1'>Test 1</a><a data-hook='test2'>Test 2</a></div>",events:{"click [data-hook=test1]":"testOne","click [data-hook=test2]":"testTwo"},props:{lastClicked:{type:"string"}},testOne:function(){this.lastClicked="test1"},testTwo:function(){this.lastClicked="test2"}});domReady(function(){window.view=new MyView});
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"domready": "1.0.7",
"ampersand-view": "7.1.4"
}
}
<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