Skip to content

Instantly share code, notes, and snippets.

@kamilogorek
Created November 27, 2014 10:29
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 kamilogorek/2b173a0839cc84b02ba5 to your computer and use it in GitHub Desktop.
Save kamilogorek/2b173a0839cc84b02ba5 to your computer and use it in GitHub Desktop.
requirebin sketch
var State = require('ampersand-state');
var X = State.extend({
props: {
foo: 'number'
},
derived: {
bar: {
deps: ['foo'],
fn: function() { return this.foo + 1; }
}
}
});
var x = new X({ foo: 1 });
x.on('change:foo', function () {
console.log(x.foo, x.bar);
});
x.foo = 2;
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}({RpLFqa:[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=_.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){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":3,"backbone-events-standalone":5,"key-tree-store":6,underscore:7}],"ampersand-state":[function(require,module,exports){module.exports=require("RpLFqa")},{}],3:[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]}},{}],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,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){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},{}],7:[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)},{}]},{},[]);var State=require("ampersand-state");var X=State.extend({props:{foo:"number"},derived:{bar:{deps:["foo"],fn:function(){return this.foo+1}}}});var x=new X({foo:1});x.on("change:foo",function(){console.log(x.foo,x.bar)});x.foo=2;
{
"name": "requirebin-sketch",
"version": "1.0.0",
"dependencies": {
"ampersand-state": "4.3.8"
}
}
<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