[sf-perl] OffTopic: Any JavaScript programmers here?
Kevin Frost
biztos at mac.com
Sat Jul 5 00:45:00 PDT 2008
Simple hash example:
var foo = { hat : 'Fedora', cat : 'Gattopardo' };
alert( 'The ' + foo.cat + ' in the ' + foo.hat );
// same as:
alert( 'The ' + foo['cat'] + ' in the ' + foo['hat'] );
Sorry, I don't have time to check your work right now, but the stuff
below does what I think you want, and is (hopefully) pretty
straightforward. It's just an illustration and shouldn't be taken as
an example of JS best practices. Also, I only checked it in Firefox 3
on Mac.
cheers
-- frosty
<html>
<head>
<title>JS example</title>
<script type="text/javascript">
FOO = {}; // minimalist namespace declaration.
FOO._origList = {}; // "hash of lists" for the Perl
hackers.
FOO.sortList = function(listID) {
var theList = document.getElementById(listID);
if (!theList) {
throw "no such list: " + listID;
}
// let's assume it's all plain text.
var items = theList.getElementsByTagName('li');
var textList = [];
for (var i=0; i < items.length; i++) {
textList[i] = items[i].firstChild.nodeValue; //
YMMV.
}
// cache the original the first time only (deep copy).
if (!FOO._origList[listID]) {
FOO._origList[listID] = [];
for (var i in textList) {
FOO._origList[listID][i] = textList[i];
}
}
// now set up the sorted list.
textList.sort();
FOO.setListFromArray(theList,textList);
};
FOO.unsortList = function(listID) {
var theList = document.getElementById(listID);
if (!theList) {
throw "no such list: " + listID;
}
// only bother if we were sorted previously.
if (FOO._origList[listID]) {
FOO.setListFromArray(theList,FOO._origList[listID]);
}
};
FOO.setListFromArray = function(theList,textArray) {
// zero out the list
while (theList.childNodes.length) {
theList.removeChild(theList.childNodes[0]);
}
// repopulate it with text
for (var i=0; i < textArray.length; i++) {
var item = document.createElement('li');
var textNode =
document.createTextNode(textArray[i]);
item.appendChild(textNode);
theList.appendChild(item);
}
}
// but really, REALLY you want to use a toolkit for this...
</script>
</head>
<body
<h1>JS example</h1>
<ol id="sortTarget">
<li>Uno</li>
<li>Dos</li>
<li>Tres</li>
</ol>
<p>
<a href="javascript:FOO.sortList('sortTarget');">sort
alpha</a>
<a href="javascript:FOO.unsortList('sortTarget');">undo</a>
</p>
<hr />
<ol id="another">
<li>Eins</li>
<li>Zwei</li>
<li>Drei</li>
</ol>
<p>
<a href="javascript:FOO.sortList('another');">sort alpha</
a>
<a href="javascript:FOO.unsortList('another');">undo</a>
</p>
</body>
</html>
More information about the SanFrancisco-pm
mailing list