Skip to content

Instantly share code, notes, and snippets.

@kentbrew
Created February 24, 2010 04:33
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 kentbrew/313105 to your computer and use it in GitHub Desktop.
Save kentbrew/313105 to your computer and use it in GitHub Desktop.
Evolving a JavaScript Widget, part 2
<!doctype html>
<html>
<head>
<title>My Javascript Widget</title>
</head>
<body>
<script src="widget.js" settings="msg=Hey%2c+cool!+It+worked!"></script>
</body>
</html>
// the evolution of a widget - part 2
// coded by Kent Brewster
// http://kentbrewster.com
// previous work explained in http://gist.github.com/306351
// in this installment:
// - see if your calling page passed any arguments
// - apply them if so; run with defaults if not
(function (d, w) {
var $ = w['kb_' + new Date().getTime()] = {};
$.d = d;
// a global pointer to window
$.w = w;
$.f = (function () {
return {
init : function (findMe) {
var i, s;
s = $.d.getElementsByTagName('SCRIPT');
for (i = 0; i < s.length; i = i + 1) {
if (s[i].src.match(findMe)) {
$.s = $.d.createElement('DIV');
s[i].parentNode.insertBefore($.s, s[i]);
s[i].parentNode.removeChild(s[i]);
$.f.houseKeep();
break;
}
}
},
houseKeep : function() {
var defaults, key
// $.a holds user arguments
$.a = $.f.parseInput(s.getAttribute('settings'));
// our defaults
defaults = {
"msg": "Hello, world."
}
// if not included in settings, use default value
for (key in defaults) {
if (defaults[key].hasOwnProperty && $.a[key] === undefined) {
$.a[key] = defaults[key];
}
}
$.s.innerHTML = $.a.msg;
},
parseInput : function (input) {
var args, i, key, pairs, q, raw, t, value;
args = {};
// require input to be a string, not an object
if (typeof input === 'string') {
raw = $.w.unescape(input);
pairs = raw.split('&');
for (i = 0; i < pairs.length; i = i + 1) {
q = pairs[i].split('=');
key = q[0];
value = q[1];
// if we see a second value for k, turn it into an array
if (typeof args[key] === 'string') {
t = args[key];
args[key] = [];
args[key][0] = t;
}
if (typeof args[key] === 'object' && args[key].length) {
// is args[key] an array? add value
args[key][args[key].length] = value;
} else {
// args[key] takes value as a string
args[key] = value;
}
}
}
return args;
}
};
}());
$.f.init(/widget\.js$/);
}(document, window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment