Skip to content

Instantly share code, notes, and snippets.

@jdbeutel
Created March 15, 2012 19:22
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 jdbeutel/2046243 to your computer and use it in GitHub Desktop.
Save jdbeutel/2046243 to your computer and use it in GitHub Desktop.
supporting quoted variable names in Agility's data-bind
// Parse data-bind string of the type '[attribute][=] variable[, [attribute][=] variable ]...'
// If the variable is not an attribute, it must occur by itself
// all pairs in the list are assumed to be attributes
// Returns { key:'model key', attr: [ {attr : 'attribute', attrVar : 'variable' }... ] }
_parseBindStr: function(str){
var obj = {key:null, attr:[]},
regex = /(?:^|,)\s*(?:([a-zA-Z0-9_\-]+)[\s=]+)?(?:"((?:[^"\\]+|\\["\\])+)"|([a-zA-Z0-9_\-]+))\s*/g,
keyAssigned = false,
matched;
RegExp.lastIndex = 0;
while ((matched = regex.exec(str)) !== null) {
// [ "attribute variable", "attribute", "variable" ]
// or [ "attribute=variable", "attribute", "variable" ]
// or
// [ "variable", "variable", undefined ]
// in some IE it will be [ "variable", "variable", "" ]
// or
// null
var variable;
if (typeof(matched[2]) === "undefined" || matched[2] === "") {
variable = matched[3];
} else {
variable = matched[2].replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
if (typeof(matched[1]) === "undefined" || matched[1] === "") {
if (keyAssigned) {
throw new Error("You may specify only one key (" +
keyAssigned + " has already been specified in data-bind=" +
str + ")");
} else {
keyAssigned = variable;
obj.key = variable;
}
} else {
obj.attr.push({attr: matched[1], attrVar: variable});
}
} // while (matched)
return obj;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment