Created
October 17, 2011 22:19
-
-
Save sfoster/1294023 to your computer and use it in GitHub Desktop.
Simplfied dojo.query wrapper to provide streamlined support for the :eq() pseudo-selector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function domQuery(selector, scopeNode){ | |
// summary: | |
// Wrap dojo.query to provide support for the :eq() pseudo-selector | |
// See: http://api.jquery.com/eq-selector/ | |
var reEqPseudo = /:eq\((\d+)\)/, | |
results = new dojo.NodeList; | |
scopeNode = scopeNode || dojo.doc.documentElement; | |
if(typeof selector !== "string" || !reEqPseudo.test(selector)){ | |
return dojo.query(selector, scopeNode); | |
} | |
var sel = selector, | |
idx, leftContext, selectorScope = scopeNode, | |
subResults = null, | |
subQueries = []; | |
// break query into sub-queries to handle the eq() | |
for(var arMatch = null; | |
(arMatch = reEqPseudo.exec( sel )); | |
sel = dojo.trim(RegExp.rightContext) | |
){ | |
if(arMatch){ | |
idx = arMatch[1]; | |
leftContext = RegExp.leftContext; | |
subQueries.push([leftContext, idx]); | |
} else { | |
break; | |
} | |
} | |
if(RegExp.rightContext){ | |
subQueries.push([RegExp.rightContext, -1]); | |
} | |
dojo.forEach(subQueries, function(pair){ | |
var sel = pair[0], | |
idx = parseInt(pair.length >= 2 ? pair[1] : -1, 10); | |
subResults = oldQuery.apply(dojo, [sel, selectorScope]); | |
// console.log("subquery: ", sel, selectorScope, subResults); | |
if(idx >= 0){ | |
selectorScope = subResults[idx]; | |
subResults = new dojo.NodeList(selectorScope); | |
} else { | |
// leave subResults as its stands | |
} | |
}); | |
results = results.concat(subResults); | |
// return aggregated results (dojo.NodeList instance) | |
return results; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment