Skip to content

Instantly share code, notes, and snippets.

@roboncode
Created October 3, 2014 14:40
Show Gist options
  • Save roboncode/2decc84554d3869f8059 to your computer and use it in GitHub Desktop.
Save roboncode/2decc84554d3869f8059 to your computer and use it in GitHub Desktop.
Training - Basic JavaScript Framework Structure & Concepts
// This represents an external JS file
var example = (function(exports){
'use strict';
exports = exports || {};
var frameworks = {};
function getInstance(name) {
name = name || 'default';
var framework = frameworks[name];
if(framework) { // is not any of these -> null, undefined, 0, false, ''
return framework;
}
framework = newFramework();
frameworks[name] = framework;
return framework;
}
// private function
var newFramework = function(){
var fm = {};
fm.version = '1.0';
fm.isString = isString;
fm.forEach = forEach;
fm.supplant = supplant;
return fm;
};
var isString = function (value) {
return typeof value === 'string';
};
var supplant = function(str, data) {
return str.replace(
/{([^{}]*)}/g,
function (a, b) {
var r = data[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
var forEach = function(list, callback) {
// for(var i in list) {
// for(var i=0;i<list.length;i+=1){
var i=0, len=list.length;
// while(i < len){
for(i;i<len;i+=1) {
// if(list.hasOwnProperty(i)) {
callback(list[i], i);
// }
// i += 1;
}
};
exports.getInstance = getInstance;
return exports;
})();
// This represents an external JS file
(function(){
String.prototype.supplant = function(data){
return this.replace(/{([^{}]*)}/g, function (a, b) {
var r = data[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
});
}
// Object.defineProperty(String.prototype, "supplant", {
// enumerable: false,
// writable: true
// });
});
// This represents our <script> code
(function(){
'use strict';
var f1 = example.getInstance();
var f2 = example.getInstance('example');
console.log('eq?', f1 === f2);
// function myCallback(item, index){
// console.log('what is', index, item);
// }
var arr = [1,2,3];
arr.abc = 123;
f1.forEach(arr, function(item, index){
console.log('what is', index, item);
});
// var str = 'Hello, ' + name + '!'
var strTemplate = 'Hello, {name}!';
var result = strTemplate.supplant({ name: 'Jim'});
console.log('result', result);
Array.prototype.isArray = true;
// Object.defineProperty(Array.prototype, "isArray", {
// enumerable: false,
// writable: true
// });
// console.log('what is the typeof array', arr.isArray);
// for(var e in arr) {
// console.log(e, arr[e]);
// }
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment