Created
December 17, 2015 10:46
-
-
Save ceving/dfe8ac1273027e75a874 to your computer and use it in GitHub Desktop.
Poor man's prepare for querySelector
This file contains 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
// | |
// Poor man's prepare for querySelector. | |
// | |
// Example: | |
// var query = prepare ('#modeler table[data-id=?] tr[data-id=?]'); | |
// query[0] = entity; | |
// query[1] = attribute; | |
// var enity_attribute_row = document.querySelector(query); | |
// | |
var prepare; | |
{ | |
let r = /^([^?]+)\?(.+)$/; // Regular expression to split the query | |
prepare = function (query, base) | |
{ | |
if (!base) base = document; | |
var q = []; // List of query fragments | |
var qi = 0; // Query fragment index | |
var v = []; // List of values | |
var vi = 0; // Value index | |
var a = []; // Array containing setters and getters | |
var m; // Regular expression match | |
while (query) { | |
m = r.exec (query); | |
if (m && m[2]) { | |
q[qi++] = m[1]; | |
query = m[2]; | |
(function (qi, vi) { | |
Object.defineProperty (a, vi, { | |
get: function() { return v[vi]; }, | |
set: function(val) { v[vi] = val; q[qi] = JSON.stringify(val); }}); | |
})(qi++, vi++); | |
} else { | |
q[qi++] = query; | |
query = null; | |
} | |
} | |
a.toString = function () { return q.join(''); } | |
return a; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment