1 2 3 4 5 6 7 8 9 10 11
var hash = new String(document.location).indexOf("#"); if(hash > 0) { page = new String(document.location).substring(hash + 1); if(page.length > 1) loadURL(page); else loadURL('news'); } else loadURL('news');
Refactorings
No refactoring yet !
chovy.myopenid.com
October 6, 2008, October 06, 2008 02:05, permalink
Get position of "#" in the location.
Check if we have a "#" at all (-1 is "none")
Get substring from starting position to end of location length.
Uses a two ternary statements to set has_hash boolean, and defining the page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* var biz; if ( some_test ) { biz = 'foo' } else { biz = 'bar' } can be written as a one-line ternary: var biz = some_test ? 'foo' : 'bar'; */ var pos_hash = document.location.indexOf("#"); var has_hash = pos_hash > 0 ? true : false; var page = has_hash ? document.location.substring(pos_hash + 1, document.location.length) : 'news'; loadURL(page);
Tien Dung
October 6, 2008, October 06, 2008 04:21, permalink
1 2 3 4 5 6 7 8
// Don't know why you need hash > 0 and page.length > 1 // In case you don't need those conditions var page = document.location.toString().split("#")[1]; LoadURL(page || 'news') // In case you need them var parts = document.location.toString().split("#"); LoadURL((parts[0].length > 0 && parts[1].length > 1) ? parts[1] : 'news')
Gabriele Lana
October 6, 2008, October 06, 2008 06:13, permalink
Not tested but should work. The function selectedAnchorOr is for better express the intent of the coder (plus, I know you have this snipped of code repeated somewhere else in your project, a function can help to keep your code more DRY and readable)
1 2 3 4 5 6 7 8 9
var selectedAnchorOr = function(url, default) { var urlWithAnchor = url.match(/^.*(#.+)$/); if (urlWithAnchor !== null) { return urlWithAnchor[1]; } return default; } loadUrl(selectedAnchorOr(document.location, "news"));
chovy.myopenid.com
October 6, 2008, October 06, 2008 19:46, permalink
Some would say you should only have one return point from a function. And there's no need to pass the location object each invocation.
1 2 3 4 5 6 7
var getAnchor = function (default) { default ||= 'news'; return document.location.toString().split( '#' )[1] || default; }; loadURL(getAnchor()); // default is used if no anchor loadURL(getAnchor("help")); // default is set to 'help' and used if no anchor
It's for detecting if you're loading the page with a #hash on the url; so the AJAX works correctly with bookmarks