working on it ...

Filters

Explore Public Snippets

Sort by

Found 77 snippets

    public by sTiLL-iLL @ SniPitz-KND  5142  4  9  42

    Vanilla KemPlates... MVC in stiches....

    real kwik model view controller example made with 100% vanilla JS
    
    ///  MY "SIGNALS" EVENT SYSTEM ////////////////
    
    //   this solution Uses my signals.js module
    
    ////////  styles  ///////////
    
    
    body {
    	font-family: Calibri;
    	width: 220px;
    }
    
    .container {
        border: 1px solid black;
        padding: 10px;
        width: 232px;
        margin: 50px auto 50px 350px;
    	border-radius: 7px;
    	background: lightgray;
    }
    
    fieldset {
    	width: 205px;
    	margin: 0 auto 3px 3px;
    	margin-right: auto;
    	margin-bottom: 6px;
    	padding: 10px;
    }
    
    h1 {
    	margin-left: 55px;
    	margin-right: auto;
    }
    
    span {
    	margin: 3px;
    }
    
    input {
    	margin-top: 2px;
    	margin-bottom: 8px;
    	width: 168px;
    	padding-left: 3px;
    }
    
    ul {
    	padding-left: 20px;
    	list-style: none;
    	color: navy;
    	overflow-x: hidden;
    }
    
    li {
    	max-width: 180px
    }
    
    
    
    /////////  Model(s)   ////////////////////////
    
    // this is the user model object
    
    var user1 = {
        name1: "Richard",
        name2: "Longwood",
        occupation: "Software Engineer",
        age: "40",
        title: 'Skillz Yo!',
        subTitle: "add a skill...",
        showSkills: true,
        skills: []
    };
    
    
    
    function UserModel (usr) {
        this.user = usr;
        this.get = function(k) {
            if (k) {
                var u = this.user;
                return u[k];
            } 
            else {
                var u = this.user;
                return u;
            }
        };
    };
    
    
    
    var User = new UserModel (user1);
    User.prototype = Signals;
    User.constructor = User;
    
    User.on = function(v, cbk) {
        this.prototype.receive(v, function(d) {
            cbk.call(this.user, d);
        });
    };
    User.emit = function(v) {
        this.prototype.signal("change", v);
    };
    User.off = function(v) {
        this.prototype.dropReceivers(v);
    };
    User.set = function(k, v) {
        if (v && v !== this.user[k]) {
            if (k == "skills") {
                this.user[k].push(v);
            } else {
                this.user[k] = v;
            }
            this.prototype.signal("change", this.user);
        }
    };
    
    
    
    // array for template strings, 
    // our template engine, and an array of target Ids.
    
    var kList = [], 
        TPE = new TPEngine(), 
        Nodz = ["t1", "t2", "t3", "t4", "t5", "t6"];
    
    
    
    // this template string is pretty bulky, 
    // so Ill keep it stashed as a string, 
    // then inject it into its target when its time.
    
    var template6 = '~>{ if(User.get("showSkills")) { :}' + 
            '~>{ for(var index in User.get("skills")) { :}' + 
            '<li><a href="#"> ~>{ User.get("skills")[index] :}' + 
            '</a></li> ~>{ } :}' + '~>{ } else { :}' + 
            '<li>none</li>' + '~>{ } :}';
    
    
    
    // this array holds the template strings.
    // the innerText is where I extract them from the mark-up
    // notice how #5 is already defined
    
    var Templates = [
        template1 = t1.innerText, 
        template2 = t2.innerText, 
        template3 = t3.innerText, 
        template4 = t4.innerText,
        template5 = t5.innerText, 
        template6
    ];
    
    
    // Now I iterate over the list of nodes and templates,
    // pull each one out per the array position and plug
    // them into the kompiler along with the property of the node that 
    // the content is assigned to, then komile into a "kPlate" template.
    // each one of these kPlates is then put into another array: "kList"
    
    Nodz.forEach(function(tmpltNd) {
        var seed = Templates.shift();
        kPlt = TPE.Template(tmpltNd, "innerHTML", seed);
        kList.push(kPlt);
    });
    
    
    
    // Here, we set up the 2-way bindings
    
    var bb = document.getElementById("btn"), 
        tgl = document.getElementById("tgl"),
        updateDom = function (d) {
            kList.forEach(function(itm) {
                TPE.BindSet(itm, d);
            });
        },
        updateModel = function (d) {
            User.set("skills", tgl.value);
            tgl.value = "";
        };
    
    
    // When the button is pressed, this handler
    // in the controller hears it, grabs the new value
    // and updates the model.
    
    bb.addEventListener("click", updateModel);
    
    
    // When the model's value is changed, it fires a change event.
    // The handler here in the controller hears it,
    // grabs the new value, and then updates the dom
     
    User.on("change", updateDom);
    
    
    // This part basicly is what runs on window ready.
    // Now that everything is all set up..
    // we iterate over the array of kPlates that we stored earlier,
    // calling BindSet on each one. This renders the mark-up
    // to the dom at lightening speed, and there ya go!
    
    kList.forEach(function(itm) {
        TPE.BindSet(itm, User);
    });
    
    
    
    
    
    
    //////////// Template kompiler (controller)  //////////////////////////////////////
    
    this.TPEngine = function() {
        var kompiler = function(templateString, model) {
            var rgx = /~>{([^:]+)?:}/g, 
            rgex = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, 
            segment = 'var r=[];\n', position = 0, 
            kompile = function(chunk, ixjs) {
                ixjs ? (segment += chunk.match(rgex) ? chunk + '\n' : 'r.push(' + chunk + ');\n') : 
                (segment += chunk != '' ? 'r.push("' + chunk.replace(/"/g, '\\"') + '");\n' : '');
                return kompile;
            };
            while (match = rgx.exec(templateString)) {
                kompile(templateString.slice(position, match.index))(match[1], true);
                position = (match.index + match[0].length);
            }
            ;
            kompile(templateString.substr(position, templateString.length - position));
            segment += 'return r.join("");';
            return new Function(segment.replace(/[\r\t\n]/g, '')).apply(model);
        }, 
        template = function(elementID, prop, templateString) {
            var c = {
                tStr: templateString,
                tProp: prop,
                tVal: document.getElementById(elementID)
            };
            return c;
        }, 
        applyBind = function(temp, model) {
            if (temp.tVal.id && temp.tStr && model) {
                template = temp;
                var el = document.getElementById(template.tVal.id);
                el[template.tProp] = kompiler(template.tStr, model);
                template.tVal = el;
            }
        };
        return {
            Template: template,
            BindSet: applyBind
        };
    };
    
    
    ///////// VIEW  //////////////////////////
    
    <!DOCTYPE html>
    <html>
    <head>
    	<title>MY MVC</title>
    </head>
      	<meta charset="utf-8" />
    	<link rel="stylesheet" href="css/stylz.css" />
    	<script src="js/signals.js"></script>
    	<script src="js/myTPlates.js"></script>
    <body>
    	<div class="container">
    		<h1 id="t1">
    			~>{ User.get("title") :} 
    		</h1>
    		<fieldset>
    			<legend id="t2">
    				~>{ User.get("subTitle") :}
    			</legend>
    			<input id="tgl" type="text" placeholder="skills"></input>
            	<button id="btn">+</button>
    			<hr><b>
    			  Name:
    			  <span id="t3">
    					~>{ User.get("name1") +" "+ User.get("name2") :}
    			  </span>
    			  </br>
    			  Age: 
    			  <span id="t4">
    					~>{ User.get("age") :}
    			 </span>
    			 </br>
    			  Dept: 
    			  <span id="t5">
    					~>{ User.get("occupation") :}
    			 </span>
    			 <hr>
    			  Skills List: 
    			 <ul id="t6">
    					~>{ User.get("skills") :}
    			 </ul></b>	
    			<hr>
    		</fieldset>
    	</div>
    </body>
    <script src="js/script1.js"></script>
    </html>
    
    
                                                                                                                

    public by sTiLL-iLL @ SniPitz-KND  4041  3  7  18

    mark out your sites, this labels the most visited link from your browser!

    get MVLinkage.js
    //  this makes a "most visited" link element.  //
    //-------------------------------------------------//
      
    function spawnMVLink(params, href, title, text, direction, provider) {
      
      var styles = getMostVisitedStyles(params, !!text),
          link = document.createElement('a');
          link.style.color = styles.color;
          link.style.fontSize = styles.fontSize + 'px';
          
      if (styles.fontFamily) {
          link.style.fontFamily = styles.fontFamily;
        }
        
      if (styles.textAlign) {
          link.style.textAlign = styles.textAlign;
        }
        
      if (styles.textFadePos) {
        var dir = /^rtl$/i.test(direction) ? 'to left' : 'to right';
        var mask = 'linear-gradient(' + dir + ', rgba(0,0,0,1),' +
            'rgba(0,0,0,1) ' + styles.textFadePos + 'px, rgba(0,0,0,0))';
            
        link.style.textOverflow = 'clip';
        link.style.webkitMask = mask;
      }
      
      link.href = href;
      link.title = title;
      link.target = 'top';
      link.tabIndex = '0';
      
      if (text) { 
        link.textContent = text;
      }
      link.addEventListener('focus', function() {
        window.parent.postMessage('linkFocused', DOMAIN_ORIGIN);
      });
      
      link.addEventListener('blur', function() {
        window.parent.postMessage('linkBlurred', DOMAIN_ORIGIN);
      });
      
      var navigate = function doNav(e) {
        
        var isFrmSrvr = 'url' in params;
        if (isFrmSrvr && params.ping) {
          ping(DOMAIN_ORIGIN + params.ping);
        }
        
        var handle = location;
        if ('pos' in params && isFinite(params.pos)) {
          handle.logMV(parseInt(params.pos, 10), provider || '');
        }
        
        if (!isFrmSrvr) {
          e.preventDefault();
          handle.navigateContentWindow(href, getEventDisposition(e));
        }
      };
      
      link.addEventListener('click', navigateFunction);
      
      link.addEventListener('keydown', function(event) {
          if (event.keyCode == 46 || event.keyCode == 8 ) {
            event.preventDefault();
            window.parent.postMessage('tileBlacklisted,' + params.pos, DOMAIN_ORIGIN);
          } 
          else if (event.keyCode == 13 || event.keyCode == 32 ) {
            navigate(event);
          }
      });
      return link;
    }            

    public by sTiLL-iLL @ SniPitz-KND  3757  4  8  19

    object data store... stuff it in yer client

    make a data tier in the browser
    
      // Local Data
       
    function DB(store, schema) {
          this.store = store;
          if (!localStorage[store] || typeof localStorage[store] == 'undefined') {
              localStorage[store] = JSON.stringify(schema|| {});
          }
          this.setData = function (key, val) {
              var lda = JSON.parse(localStorage[this.store]);
              doUpdate(ldta, key, val);
              localStorage[store] = JSON.stringify(ldta);
          };
          this.getData = function (key) {
              var ldta = JSON.parse(localStorage[this.store]);
              if (key) {
                  return pathGet(ldta, key);
              }
              return ldta;
          };
          this.reset = function (schema) {
              localStorage[this.store] = JSON.stringify(schema || {});
          };
          this.delete = function() {
              localStorage.removeItem(this.store);
          };
          var doUpdate = function (ob, kStr, val) {
              var kpth = keyStr.split('.'),
              i = 0, lstIdx = kpth.length - 1;
              for (;i < lstIdx; ++i) {
                  var key = kpth[i];
                  if (!(key in ob)) {
                      ob[key] = {};
                  }
                  ob = ob[key];
              }
              ob[kpth[lstIdx]] = val;
          };
          var pathGet = function (obj, key, leftOvrs) {
              if ( leftOvrs === undefined ) {
                  leftOvrs = key.split('.');
              }
              var cur = leftOvrs.shift();
              if ( typeof(obj) == 'object' && obj[cur] !== undefined ) {
                  if ( leftOvrs.length === 0 ) {
                      return obj[cur];
                  }
                  else if ( typeof(obj[cur]) == 'object' ) {
                      return arguments.callee(obj[cur], undefined, leftOvrs);
                  }
              }
              return null;
          };
      }
                

    public by sTiLL-iLL @ SniPitz-KND  4152  2  7  19

    Try this HashMap! ++ ++ ++

    hash-table and key generator,.. uuids, cool extedo method, oh yeah, it also supports using objects as keys!!!
    ///////////////////////////
    // unique ids puhleez!!! //
    ///////////////////////////
    
    function nextUid() {
      var index = uid.length;
      var digit;
    
      while(index) {
        index--;
        digit = uid[index].charCodeAt(0);
        if (digit == 57 /*'9'*/) {
          uid[index] = 'A';
          return uid.join('');
        }
        if (digit == 90  /*'Z'*/) {
          uid[index] = '0';
        } else {
          uid[index] = String.fromCharCode(digit + 1);
          return uid.join('');
        }
      }
      uid.unshift('0');
      return uid.join('');
    }
    
    /////////////////////////////////////////////
    // Set or clear the hashkey for an object. //
    ////////////////////////////////////////////
    
    function setHashKey(obj, h) {
      if (h) {
        obj.$$hashKey = h;
      }
      else {
        delete obj.$$hashKey;
      }
    }
    
    function extend(dest) {
      var h = dst.$$hashKey;
      forEach(arguments, function(obj){
        if (obj !== dest) {
          forEach(obj, function(value, key){
            dest[key] = value;
          });
        }
      });
      setHashKey(dest,h);
      return dset;
    }
    
    function int(str) {
      return parseInt(str, 10);
    }
    
    
    function inherit(parent, extra) {
      return extend(new (extend(function() {},
        { prototype:parent })
      )(), extra);
    }
    
    ///////////////////////////////
       // Heath'sHash(map) //
       // keys & values //
     //////////////////////////////
    
    function hashKey(obj) {
      var objType = typeof obj,
          key;
    
      if (objType == 'object' && obj !== null) {
        if (typeof (key = obj.$$hashKey) == 'function') {
          // must invoke on object to keep the right this
          key = obj.$$hashKey();
        } else if (key === undefined) {
          key = obj.$$hashKey = nextUid();
        }
      } else {
        key = obj;
      }
    
      return objType + ':' + key;
    }
    
    ////////////////////////////////////////////
     
    function HashMap(array){
      forEach(array, this.put, this);
    }
    
    HashMap.prototype = {
      put: function(key, value) {
        this[hashKey(key)] = value;
      },
      get: function(key) {
        return this[hashKey(key)];
      },
      remove: function(key) {
        var value = this[key = hashKey(key)];
        delete this[key];
        return value;
      }
    };
                

    public by sTiLL-iLL @ SniPitz-KND  4759  3  7  16

    kwik dirty arraySort....

    kwik example of a complex array sort
    // sort a complex array
    
    var mehAry = [{id: 140, name: "abc", age: "twenty"},
                  {id: 62009, name: "def", age: "thirty"},
                  {id: 3030, name: "ghi", age: "forty" },
                  {id: 455, name: "jkl", age: "fifty" }];
          
    function complexSort (itm1, itm2) {
        var a = itm1.id, b = itm2.id;
        return (a - b);
    }
    
    var sortedArray = mehAry.sort(complexSort);  
    
    //  sortedArray = [{id: 140, name: "abc", age: "twenty"},{id: 455, name: "jkl", age: "fifty" },
    //                 {id: 62009, name: "def", age: "thirty"},{id: 3030, name: "ghi", age: "forty" }];                        

    public by sTiLL-iLL @ SniPitz-KND  532512  3  8  21

    Ajax again?? Wrap it!! XHR Agent 4Ya

    XHR wrapper! object pooling and cueing!!! EveryOneZ dOing IT!
    
    var myXHR = {
           ESpec: function (wrap, evt) {
               return { xhrWrap: wrap, event: evt };
           },
           Agent: function(maxConnect) {
               var bCued = [], slf = this,
                   max = maxConnect || 3;
                   this.curCon = 0;
               function inCue() {
                   if (self.bCued < max) {
                       self.bCued++;
                       var itm = is.Readied.shift();
                       itm.evt.addEventListener(['EVENT_COMPLETE'], 
                         function (e) {
                             self.bCued--;
                             if (this.Readied.length !== 0) {
                               inCue();
                             }
                         });
                       itm.wrap.call(itm, args, itm.evt);
                    }
               }
               this.Readied = function (ESpec) {
                   bCued.push(ESpec);
                   inCue();
                   return ESpec.evt;
               };
            }
       };
    
                

    public by sTiLL-iLL @ SniPitz-KND  4705  12  8  28

    my skreenScooper in pure js. schweet YO!

    self executing module. skreen shots from DA BROWSAH!
    // javascript screenshot in your face!!!
    
    (function (wIn) {
    	function toAbso(urlz) {
    		if (!urlz.length) {
    		return [];
    	}
    
    	var attrNm = 'href', imgPrto = Object.create(HTMLImageElement.prototype),
    	    scptPrto = Object.create(HTMLScriptElement.prototype);
    	if (urlz[0].prototype === imgPrto || urlz[0].prototype === scptPrto) {
    		attrNm = 'src';
    	}
    
    	urlz = [].map.call(urlz, function (el, i) {
    	  var attr = el.getAttribute(attrNm);
    	  if (!attr) {
    		  return;
    	  }
    	  var dta = /^(https?|data):/i.test(attr);	
    	  if (dta) {
    		  return el;
    	  }
    	  else {
    		  return el;
    	  }});
    	  
    	return urlz;
    }
    
    function shootIt() {
    	toAbso(document.images);
    	toAbso(document.querySelectorAll("link[rel='stylesheet']"));
    	
      var sht = document.documentElement.cloneNode(true),
          shts = sht.style,
          shtd = sht.dataset,
          hed = sht.querySelector('head'),
          scpt = document.createElement('script');
          b = document.createElement('base');
          b.href = document.location.protocol + '//' + location.host;
          hed.insertBefore(b, hed.firstChild);
    
    	shtd.scrollX = wIn.scrollX;
    	shtd.scrollY = wIn.scrollY;
    	shts.pointerEvents, shts.userSelect, shts.webkitUserSelect,
    	shts.mozUserSelect, shts.msUserSelect, shts.oUserSelect = 'none';
    	shts.overflow = 'hidden';
    	scpt.textContent = '(' + onReadyGo.toString() + ')();';
    	sht.querySelector('body').appendChild(scpt);
    	
    	var blb = new Blob([sht.outerHTML], {
    		type: 'text/html'
    	});
    	return blb;
    }
    
    var seeIt = function() {
    	wIn.URL = wIn.URL || wIn.webkitURL;
    	wIn.open(wIn.URL.createObjectURL(shootIt()));
    };
    
    var onReadyGo = function() {
    	wIn.addEventListener('DOMContentLoaded', function (e) {
    		var xx = document.documentElement.dataset.scrollX || 0;
    		var yy = document.documentElement.dataset.scrollY || 0;
    		wIn.scrollTo(xx, yy);
    	});
    };
    
    wIn.seeIt = seeIt;
    
    })(window);            

    public by sTiLL-iLL @ SniPitz-KND  3596  4  8  25

    Enumerator.js... behind every enumeration you'll find a good Iterator. I guess.... LoL

    the future is now!
    // slick as snot Enumerable type!!!! yeah!
    
    var Enum = {
          create: function (collection) {
            var index=0;
            return {
              next: function() {
                if (index < collection.length) {
                  return ({ value: collection[index++], done: false });
                }
                else {
                  return ({ value: null, done: true});
                }
             }
          };
       }
    };
    
    // use it like this... (strings, bool, numbers, all gewd!)
    
    var arr=['rtJKvE', '!!@wrh', 433, 'yippe', 216,'PRdUrg', 3038, 'whaa?'],
      it = Enumerator.create(arr),
      primer = 0;
    
    while(primer !== null) {
      primer = it.next().value;
    	document.writeLine(primer);
    }
                

    public by sTiLL-iLL @ SniPitz-KND  5322  1  9  20

    tHe SinMpLEtOn KAcHeR MoDuLE!

    keep it simpleton stoopid!!! LoL
    
    var evt = require("events").EventEmitter,
    	fs = require('fs'),
    	url = require("url"),
    	path = require("path"),
    	cache = [],
    	cacheMax = 500,
    	intervalCache = 3600;
    	
    var mime = {
    	".txt": "text/plain",
    	".css": "text/css",
    	".js": "text/javascript",
    	".htm": "text/html",
    	".html": "text/html",
    	".jpeg": "image/jpeg",
    	".jpg": "image/jpeg",
    	".png": "image/png",
    	".gif": "image/gif",
    	".ico": "image/x-icon",
        ".xml": "text/xml",
    	".rss": "application/rss+xml",
        ".json": "application/json"
    };
    
    function setCache(path, dta) {
    	if (cache.length < cacheMax) {
    		cache[path] = { data: dta, mtime: 0 };
    	}
    }
    
    function serveStat(request, response) {
    	var fname = path.basename(url.parse(request.url, true).pathname),
    		ex = path.extname(request.url),
    		dname = path.dirname(request.url);
    		fname = (fname === '' && dname == '/')? fname += "index.html": fname;
    	var pth = path.join(__dirname + dname, fname).toLowerCase();
    	if (cache[pth] !== undefined) {
    		response.writeHead(200, {
    			"Content-Type": mime[ex]
    		});
    		response.end(cache[pth].data);
    	}
    	else {
    		var rStrm = fs.createReadStream(pth);
    		rStrm.on('open', function () {
    			rStrm.pipe(response);
    		});
    		
    		rStrm.on('end', function () {
    			response.end();
    			fs.readFile(pth, function (err, dta) {
    				if (!err) {
    					var bf = new Buffer(dta).toString('utf-8');
    					setCache(pth, bf, mime[ex]);
    				}
    			});
    		});
    		
    		rStrm.on('error', function (err) {
    			response.end(JSON.stringify(err));
    		});
    	}
    }
    
    function check(pth) {
    	fs.stat(pth, function (err, stats) {
    		if (!err) {
    			if (cache[pth].mtime != stats.mtime.getTime()) {
    				fs.readFile(pth, function (err, dta) {
    					if (!err) {
    						cache[pth].data = dta;
    						cache[pth].mtime = stats.mtime.getTime();
    					}
    				});
    			}
    		}
    	});
    }
    
    function doInterval(code) {
    	var id = null;
      if(code !== true) {
        try {
          id = setInterval(function () {
            for (var pth in cache) {
              check(pth);
            }
          }, intervalCache);
        }
        catch(err) {
          console.log("error starting Kache: " + err);
        }
      }
    	else {
    		return clearInterval(id);
    	}
    }
    
    var setMaxFileCount = function(count) {
    	cacheMax = count;
    	return cacheMax;
    };
    
    var setCacheInterval = function(milliSeconds) {
    	intervalCache = milliSeconds;
    	return intervalCache;
    };
    
    var start = function() {
    	return doInterval();
    };
    
    exports.start = start;
    exports.setMaxFileCount = setMaxFileCount;
    exports.setCacheInterval = setCacheInterval;            

    public by sTiLL-iLL @ SniPitz-KND  3513  0  7  19

    KachingFetch.js get it boy! woof! good dog....

    I modeled it after jquery's "getScript" only better.... cause it caches!!!
    
    // caching script fetcher  //
     
    var futrs = {};
     
     var ajaxFetch = function( url, cBak ) {
         if ( !futrs[ url ] ) {
             futrs[ url ] = $.Deferred(function( defer ) {
                 $.getScript( url )
                     .then( defer.resolve, defer.reject );
                 }).promise();
           }
         return futrs[ url ].done( cBak );
     };
     
    /*-----------------------------------------------------------------------*/
     
        // <<  use it! >>
      ajaxFetch('//totalPorn247.com/freeVideos/Tits+Ass?=199BOOBzInVIEW.js', cBak);
     
      function cBak(resp) {
          if(resp.length > 0) {
              var dd = document.querySelector('#resultDiv');
              dd.innerHTML = renderDirtyWords(a, z, 125);                        
          }  
      }
            
                
    • Public Snippets
    • Channels Snippets