sTiLL-iLL
sTiLL-iLL
Reputation Top 1%
heath dernovich
Something about myself here..... er,.. um.. uhh.

yup. #/ 8-!?) i like stuff... hmmm
106 Snippets  (5th place)
Published
1 Channel
Created
10 Channels
Following
Jan 14, 2016
Last Visit
Aug 23, 2014
Registered
48927 points  (6th place)
Reputation
Top 1% Publisher
Junior Code Generator
Serious Code Generator
Senior Code Generator
Master Code Generator
Guru Code Generator
Senior Publisher
Master Publisher
Guru Publisher
Junior Topic Hub
Junior Trend Maker
Serious Trend Maker
Senior Trend Maker
Master Trend Maker
Junior Influencer
Serious Influencer
Senior Influencer
Junior Judge
Serious Judge
Senior Judge
Master Judge
Master Popular Coder
Guru Popular Coder
Junior Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Famous Coder
Guru Famous Coder
Senior Wise Coder

Recent Snippets See all snippets by sTiLL-iLL

public by sTiLL-iLL @ SniPitz-KND created Feb 11, 2015  5062  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 created Oct 25, 2014  3972  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 created Nov 6, 2014  3694  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 created Oct 30, 2014  4105  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 created Dec 18, 2014  4701  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" }];                        
;