UNPKG

@danielkalen/simplybind

Version:

Magically simple, framework-less one-way/two-way data binding for frontend/backend in ~5kb.

34 lines (33 loc) 16.7 kB
(function(){var w,k,m,H,r,p,t,x,I,y,z,J,n,A,l,K,B,C,g,D,E,u,F,v,G,h,q;r="push pop shift unshift splice reverse sort".split(" ");J=function(){return"sb_"+Math.floor(1E12*(1+Math.random())).toString(16)};n=function(){return Object.create(null)};B=function(a){return a instanceof k};u=function(a,b,c){var d,e;for(d in b)e=b[d],null!=l[d]&&(a.options[d]=e);if(c)return a.makePropertyLive()};t={textNodes:{},object:{set:function(a){var b,c;c=a.selector||a.property;if(a.object._sb_map)return a.object._sb_map[c]= a.ID;b={};b[c]=a.ID;return Object.defineProperty(a.object,"_sb_map",{configurable:!0,value:b})},get:function(a,b){if(a._sb_map&&a._sb_map[b])return p[a._sb_map[b]]}},simpleObject:{set:function(a){return Object.defineProperty(a.object,"_sb_ID",{configurable:!0,value:a.ID})},get:function(a){return p[a._sb_ID]}}};z=/[.*+?^${}()|[\]\\]/g;E=D=null;F=function(){var a,b,c;c=l.placeholderStart.replace(z,"\\$&");a=l.placeholderEnd.replace(z,"\\$&");b="[^"+a+"]+";D=new RegExp(c+"("+b+")"+a,"g");return E=new RegExp(""+ c+b+a,"g")};H=function(a,b,c){var d,e,f,g,h;h="";f=e=0;for(g=a.length;e<g;f=++e)d=a[f],h+=d,c[f]&&(h+=b[c[f]]);return h};v=function(a,b){var c;c=A();throw Error("SimplyBind: "+((b?a:y[a])+("\n\nCall Source:\n"+c)));};q=function(a){var b;if(!l.silent)return b=A(),a=y[a],console.log("SimplyBind: "+(a+("\n\nCall Source:\n"+b)))};h=function(a){return v("You can't use/invoke ."+a+"() at this stage",!0)};G=function(a,b){return v("Invalid argument/s ("+b+") passed to ."+a+"()",!0)};A=function(){return Error().stack.split("\n").slice(3, 10).map(function(a){return a.replace(I,function(a,c,d){return"@ "+d})}).join("\n")};I=/[@(?:\wat\s)](.*)\/(.+)$/;Error.prototype.stack="\n\n\n";y={invalidParamName:"SimplyBind() and .to() only accept a function, an array, a bound object, a string, or a number.",fnOnly:"Only functions are allowed for .transform/.condition/All()",badEventArg:"Invalid argument number in .ofEvent()"};p={};l={silent:!1,liveProps:!0,dispatchEvents:!1,updateEvenIfUndefined:!1,updateEvenIfSame:!1,updateOnBind:!0,mutateInherited:!1, trackArrayChildren:!1,simpleSelector:!1,promiseTransforms:!1,placeholderStart:"{{",placeholderEnd:"}}"};F();m=function(a,b,c){if(!a&&0!==a||"string"!==typeof a&&"number"!==typeof a&&"function"!==typeof a&&!(a instanceof Array))B(a)||v("invalidParamName");return"object"!==typeof a||a instanceof Array?new k(null,0,null,a,c,b):new k(a._,1)};w=function(a,b,c,d,e,f,g,h){var k,l;for(k in g)l=g[k],this[k]=l;this.options=f;this.type=a;this.ID=J();this.property=c;this.selector=b;this.object=d;this.objects= e;this.value=this.valueOriginal=null;this.deps=[];this.depsMap={1:n(),2:n()};this.depsPholders=n();this.myPholders=n();this.transforms=n();this.conditions=n();this.attachedEvents=[];"Event"!==this.type&&(a=this.fetchDirectValue(null,h),"undefined"===typeof a&&"ObjectProp"===this.type&&(this.object[this.property]=a=null),this.value=this.valueOriginal=a,this.placeholder&&!this.pholderValues&&this.scanForPholders());this.makePropertyLive();this.attachEvents();this.object instanceof Array&&"Array"!== this.type&&(this.arrayBinding=a=t.simpleObject.get(this.object))&&a.options.trackArrayChildren&&-1===a.trackedChildren.indexOf(this.property)&&(a.trackedChildren.push(this.property),m(this.property).of(this.object).to(a.updateSelf));return p[this.ID]=this};k=function(a,b,c,d,e,f){var g;this.stage=b||0;b=c||{};for(g in b)c=b[g],this[g]=c;this.proxies=this.proxies&&this.proxies.length?this.proxies:this.proxied?[this.proxied]:[];null==this.state&&(this.state={});switch(this.stage){case 0:this.optionsPassed= f||(f={});this.options={};for(g in l)this.options[g]=null!=f[g]?f[g]:l[g];"function"===typeof d?(a=this.setObject(d,"Func",!0,e),this.stage=1):d instanceof Array?(a=this.setObject(d,"Array",!0),this.stage=1):("number"===typeof d&&(d=d.toString()),this.selector=this.property=d,this.options.simpleSelector||(-1!==this.selector.indexOf(":")&&(d=this.property.split(":"),this.descriptor=d[0],this.property=d[1]),-1!==this.selector.indexOf(".")&&(d=this.property.split("."),this.property=d[0],this.placeholder= d.slice(1).join(".")),this.selector=this.property));break;case 1:if(!a){a:switch(!1){case !this.state.hasEventName:f="Event";break a;default:f="ObjectProp"}a=this.setObject(d,f)}}Object.defineProperties(this,{_:{value:a},ID:{get:function(){return a.ID}},value:{get:function(){return a.value}},original:{get:function(){return a.objects||a.object}},dependents:{get:function(){return a.deps.slice().map(function(a){return a.object})}},"new":{value:function(b,c){return new k(a,b,this.getState(),c,e)}}}); return this};w.prototype={makePropertyLive:function(a){var b,c,d,e,f,g,h,k;if(this.options.liveProps)if(b=this,"ObjectProp"===this.type){if(f=Object.getOwnPropertyDescriptor(this.object,this.property),(k=this.options.mutateInherited||f&&f.configurable)&&!this.isLiveProp||a)return this.isLiveProp=!0,d=(null!=f?null!=(g=f.get)?g.bind(this.object):void 0:void 0)||function(){return b.value},e=(null!=f?null!=(h=f.set)?h.bind(this.object):void 0:void 0)||function(){},Object.defineProperty(this.object,this.property, {configurable:!0,enumerable:null!=f?f.enumerable:void 0,get:function(){return d()},set:function(a){b.setValue(a);return e(a)}})}else if("Array"===this.type&&(this.isLiveProp||(this.isLiveProp=!0,r.forEach(function(a){return Object.defineProperty(b.value,a,{configurable:!0,value:function(){var c;c=Array.prototype[a].apply(b.value,arguments);b.updateAllDeps();return c}})})),this.options.trackArrayChildren&&!this.trackedChildren))return this.trackedChildren=[],this.updateSelf=function(){return b.updateAllDeps()}, c={updateOnBind:!1},this.value.forEach(function(a,d){b.trackedChildren.push(""+d);return m(d,c).of(b.value).to(b.updateSelf)})},addDep:function(a,b,c){this.depsMap[1][a.ID]||(this.depsMap[1][a.ID]=a._,this.deps.push(a._));b.placeholder?this.myPholders[a.ID]=b.placeholder:this.myPholders[a.ID]&&delete this.myPholders[a.ID];a.placeholder&&(this.depsPholders[a.ID]=a.placeholder);c?this.depsMap[2][a.ID]=a._:a._.depsMap[1][this.ID]&&(a._.addDep(b,a,!0),this.addDep(a,b,!0));return this},removeDep:function(a, b){this.depsMap[1][a.ID]&&(this.deps.splice(this.deps.indexOf(a),1),delete this.depsMap[1][a.ID],delete this.depsPholders[a.ID]);if(b)return a.removeDep(this),delete this.depsMap[2][a.ID]},removeAllDeps:function(a){var b,c,d,e;e=this.deps.slice();c=0;for(d=e.length;c<d;c++)b=e[c],this.removeDep(b,a);if(a||0===Object.keys(this.depsMap[2]).length)return this.destroy()},destroy:function(){var a,b,c,d;delete p[this.ID];if("ObjectProp"===this.type||"DOMText"===this.type)Object.defineProperty(this.object, this.property,{value:this.value,writable:!0}),delete this.object._sb_map,delete this.object._sb_ID;else if("Event"===this.type){d=this.attachedEvents;b=0;for(c=d.length;b<c;b++)a=d[b],this.unRegisterEvent(a,this.customEventMethod.remove);delete this.object._sb_map}else if("Array"===this.type)for(delete this.object._sb_ID,a=0,b=r.length;a<b;a++)c=r[a],delete this.object[c];else"Func"===this.type&&delete this.object._sb_ID},fetchDirectValue:function(a,b){null==a&&(a=this.type);switch(a){case "Func":if(!b)return this.object(); break;case "Array":return this.object;default:return this.object[this.property]}},setValue:function(a,b,c,d){var e,f;null==c&&(c=this);e=b?this.pholderValues[b]:this.value;this.selfTransform&&(a=this.selfTransform(a));e=a!==e||this.options.updateEvenIfSame;f="undefined"!==typeof a||this.options.updateEvenIfUndefined;if((e&&f||this.isEvent)&&"Array"!==this.type){b?(this.pholderValues[b]=a,this.value=a=H(this.pholderContexts,this.pholderValues,this.pholderIndexMap)):this.value=a;switch(this.type){case "ObjectProp":this.isLiveProp|| (this.object[this.property]=a);break;case "Func":b=this.valuePassed;this.valuePassed=a;this.value=this.object(a,b);break;case "Event":d||(this.emitCauser=c,this.emitEvent(a),this.emitCauser=null)}d&&this.emitCauser||this.updateAllDeps(c)}},updateAllDeps:function(a){var b,c,d,e;if(this.deps.length){if(this.throttleRate){if(+new Date-this.lastUpdate<this.throttleRate)return clearTimeout(this.throttleTimeout),this.throttleTimeout=setTimeout(function(b){return function(){return b.updateAllDeps(a)}}(this), this.throttleRate);this.lastUpdate=+new Date}e=this.deps;c=0;for(d=e.length;c<d;c++)b=e[c],this.updateDep(b,a)}},updateDep:function(a,b){var c,d,e,f;c=null===this.value&&"Event"===this.type;if(!(b&&(b===a||b!==this&&b.depsMap[1][a.ID])||c)&&(b||(b=this),c=(c=this.myPholders[a.ID])?this.pholderValues[c]:this.value,e=(d=this.depsPholders[a.ID])?a.pholderValues[d]:a.value,f=c,f=this.applyTransform(a,d,c,e),this.checkCondition(a,d,c,e)))return this.options.promiseTransforms&&null!=f&&"function"===typeof f.then? f.then(function(c){return function(c){return a.setValue(c,d,b)}}(this)):a.setValue(f,d,b)},processTransform:function(a,b){var c,d,e,f;if("function"!==typeof a)return q("fnOnly");c=0;for(d=b.length;c<d;c++)e=b[c],f=e.ID,f+=e.placeholder?"."+e.placeholder:"",this.addTransform(f,a),e=e._,this.depsMap[2][e.ID]&&e.addTransform(this.ID,a),(this.options.updateOnBind||"Func"===this.type)&&this.updateDep(e);return!0},applyTransform:function(a,b,c,d){return this.hasTransforms?(a=a.ID,b&&(a+="."+b),this.transforms[a]? this.transforms[a](c,d):c):c},addTransform:function(a,b){this.hasTransforms=!0;return this.transforms[a]=b},processCondition:function(a,b){var c,d,e,f;if("function"!==typeof a)return q("fnOnly");c=0;for(d=b.length;c<d;c++)e=b[c],f=e.ID,f+=e.placeholder?"."+e.placeholder:"",this.addCondition(f,a),e=e._,this.depsMap[2][e.ID]&&e.addCondition(this.ID,a);return!0},checkCondition:function(a,b,c,d){return this.hasConditions?(a=a.ID,b&&(a+="."+b),this.conditions[a]?this.conditions[a](c,d):!0):!0},addCondition:function(a, b){this.hasConditions=!0;return this.conditions[a]=b},scanForPholders:function(){var a;this.pholderValues=n();this.pholderIndexMap=n();this.pholderContexts=[];if("string"===typeof this.valueOriginal)return this.pholderContexts=this.valueOriginal.split(E),a=0,this.value=this.valueOriginal.replace(D,function(b){return function(c,d){b.pholderIndexMap[a++]=d;return b.pholderValues[d]=d}}(this))},addPollInterval:function(a){this.removePollInterval();return this.pollInterval=setInterval(function(a){return function(){var c; c=a.fetchDirectValue();return a.setValue(c)}}(this),a)},removePollInterval:function(){clearInterval(this.pollInterval);return this.pollInterval=null},attachEvents:function(){if("Event"===this.type)return this.registerEvent(this.eventName,this.customEventMethod["in"])},registerEvent:function(a,b){if(-1===this.attachedEvents.indexOf(a))return this.attachedEvents.push(a),this.invokeEventMethod(a,b||"on","on")},unRegisterEvent:function(a,b){var c;c=this.attachedEvents.indexOf(a);if(-1!==c)return this.attachedEvents.splice(c, 1),this.invokeEventMethod(a,b||"removeListener","removeListener")},invokeEventMethod:function(a,b,c){var d;d=this.object;d[b]||(b=c);this.eventHandler||(this.eventHandler=K.bind(this));return"function"===typeof d[b]?d[b](a,this.eventHandler):void 0},emitEvent:function(a){var b,c;c=this.object;b=this.customEventMethod.out||"emit";c[b]||(b="emit");return c[b](this.eventName,a)}};K=function(){var a;a="Event"===this.type?arguments[this.property]:this.fetchDirectValue();return this.setValue(a,null,this.emitCauser, !0)};k.prototype={of:function(a){var b;0!==this.stage&&2!==this.stage&&h(g[0]);"object"!==typeof a&&"function"!==typeof a&&G(g[0],a);B(a)&&(a=a.object);2===this.stage&&(b=this.proxies.indexOf(this.proxied),this.proxied=this.proxied.of(a),this.proxies[b]=this.proxied,this.state.hasInitialBinding=!0,this.state.hasTransform=!1,this._.addDep(this.proxied,this),C(this._,this.proxied._));return this["new"](this.stage+1,a)},ofEvent:function(a,b,c){0!==this.stage||this.state.hasEventName?h(g[1]):a&&"string"=== typeof a?isNaN(parseInt(this.property))&&q("badEventArg"):G(g[1],a);this.state.hasEventName=!0;this.eventName=a;this.selector=this.property+"#"+this.eventName;this.customEventMethod={"in":b,out:c};return this},to:function(a,b){var c;(1!==this.stage||this.state.hasInitialBinding)&&h(g[2]);this.proxied=x(this,a,b);0===this.proxied.stage?c=2:(c=3,this.state.hasInitialBinding=!0);return this["new"](c)},and:function(a,b){var c;3===this.stage&&this.state.hasInitialBinding&&!this.state.hasMultiTransform|| h(g[3]);this.proxied=x(this,a,b);this.proxies=this.proxies.concat(this.proxied);0===this.proxied.stage?c=2:(c=3,this.state.hasTransform=!1);return this["new"](c)},toEvent:function(a,b,c,d){1!==this.stage&&h(g[4]);this.proxied=m(0,d).ofEvent(a,c,b);return this["new"](2)},chainTo:function(a,b){3!==this.stage&&h(g[5]);return m(this.proxied).to(a,b)},set:function(a){0!==this.stage&&2!==this.stage||h(g[6]);this._.setValue(a,this.placeholder);return this},get:function(){0!==this.stage&&2!==this.stage|| h(g[7]);return this.placeholder?this._.pholderValues[this.placeholder]:this._.value},transformSelf:function(a){(1!==this.stage||1===this.stage&&"Array"===this._.type)&&h(g[8]);"function"!==typeof a?q("fnOnly"):(this._.selfTransform=a,this._.options.updateOnBind&&this.set(this.value));return this},transform:function(a){(3!==this.stage||this.state.hasTransform||this.state.hasMultiTransform)&&h(g[9]);this.state.hasTransform=this._.processTransform(a,[this.proxied])||!1;return this["new"](3)},transformAll:function(a){(3!== this.stage||this.state.hasTransform||this.state.hasMultiTransform)&&h(g[10]);this.state.hasMultiTransform=this._.processTransform(a,this.proxies)||!1;return this["new"](3)},condition:function(a){3!==this.stage&&h(g[11]);this._.processCondition(a,[this.proxied]);return this["new"](3)},conditionAll:function(a){3!==this.stage&&h(g[12]);this._.processCondition(a,this.proxies);return this["new"](3)},bothWays:function(a){var b,c,d;(3!==this.stage||this.state.hasMultiTransform)&&h(g[13]);b=this.proxied._.addDep(this, this.proxied,!0);d=this._.transforms[this.proxied.ID];c=this._.conditions[this.proxied.ID];(d||a)&&(d="function"===typeof a?a:d)&&!1!==a&&b.addTransform(this.ID,d);c&&b.addCondition(this.ID,c);this._.addDep(this.proxied,this,!0);return this},unBind:function(a){var b,c,d,e;3!==this.stage&&h(g[14]);e=this.proxies;b=0;for(c=e.length;b<c;b++)d=e[b],this._.removeDep(d._,a);return this},pollEvery:function(a){3===this.stage&&"Event"!==this._.type||h(g[15]);this._.addPollInterval(a);return this},stopPolling:function(){3!== this.stage&&h(g[16]);this._.removePollInterval();return this},updateDepsOnEvent:function(a,b){3!==this.stage&&h(g[17]);this._.registerEvent(a,b);return this},removeEvent:function(a,b){3!==this.stage&&h(g[18]);this._.unRegisterEvent(a,b);return this},throttle:function(a){1!==this.stage&&3!==this.stage&&h(g[19]);"number"===typeof a&&a?this._.throttleRate=a:!1===a&&delete this._.throttleRate;return this},setOption:function(a,b){var c,d,e,f,g;e=(c={},c[""+a]=b,c);u(this._,e,!0);g=this.proxies;c=0;for(d= g.length;c<d;c++)f=g[c],u(f._,e,!0);return this}};k.prototype.update=k.prototype.set;k.prototype.twoWay=k.prototype.bothWays;k.prototype.pipe=k.prototype.chainTo;g=Object.keys(k.prototype);x=function(a,b,c){null==c&&(c={});a.proxied=b=m(b,c,!0);0!==b.stage&&(a._.addDep(b,a),C(a._,b._));return b};C=function(a,b){if(a.options.updateOnBind||"Func"===a.type)return a.updateDep(b)};Object.defineProperties(k.prototype,{setObject:{value:function(a,b,c,d){var e;this.object=a;c=c?"simpleObject":"object";if(e= t[c].get(a,this.selector))return this.placeholder&&!e.pholderValues&&(e.valueOriginal=e.fetchDirectValue(),e.scanForPholders()),"ObjectProp"!==e.type||this.property in a||e.makePropertyLive(!0),u(e,this.options,!0),e;a=new w(b,this.selector,this.property,this.object,this.objects,this.options,{isDom:this.isDom,isDomInput:this.isDomInput,placeholder:this.placeholder,eventName:this.eventName,customEventMethod:this.customEventMethod,isEvent:this.state.hasEventName},d);t[c].set(a);return a}},getState:{value:function(){return{options:this.options, selector:this.selector,object:this.object,property:this.property,descriptor:this.descriptor,placeholder:this.placeholder,eventName:this.eventName,customEventMethod:this.customEventMethod,proxied:this.proxied,proxies:this.proxies,state:this.state}}}});Object.defineProperties(m,{version:{value:"1.2.0"},options:{get:function(){var a,b,c;a={};for(b in l)c=l[b],a[b]=c;return a}}});m.setOption=function(a,b){if(null!=l[a]&&(l[a]=b,-1!==a.indexOf("place")))return F()};m.setOptions=function(a){var b,c;for(b in a)c= a[b],m.setOption(b,c)};m.unBindAll=function(a,b){var c,d,e;if(a&&("object"===typeof a||"function"===typeof a)&&(e=a._sb_map,a._sb_ID&&p[a._sb_ID].removeAllDeps(b),e))for(d in e)c=e[d],p[c].removeAllDeps(b)};return module.exports=m})();