Created
July 7, 2013 06:17
-
-
Save kitsonk/5942517 to your computer and use it in GitHub Desktop.
Syntax Checking Expression
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
/** This expression checking syntax is not currently part of MDV, which pidgin/tmpl is built upon, and so it is | |
* used here as a custom syntax. It is very handy and might be incorporated directly into pidgin in the | |
* future. | |
*/ | |
/** | |
* Matches a string that is enclosed within parens `(...)` | |
* @type {RegExp} | |
*/ | |
var expressionRE = /^\(([^\)]*)\)$/; | |
/** | |
* Takes an expression as a string, evaluates it, and returns a boolean result. | |
* @param {String} expression The string expression being evaluated (e.g. `"foo === 'bar'"`) | |
* @param {Object} vars A hash of variables that should be used in conjunction with the expression. | |
* @return {Boolean} The result of the expression | |
*/ | |
function checkExpression(expression, vars) { | |
vars = vars || {}; | |
/** | |
* A proxy Function constructor function that allows the creation of a function via Function.apply | |
* @param {Array} args The array of arguments to be passed to the Function constructor | |
*/ | |
function F(args) { | |
return Function.apply(this, args); | |
} | |
F.prototype = Function.prototype; | |
var args = Object.keys(vars), | |
vals = [], | |
i; | |
// Create a snippet of code that returns a boolean value for the supplied expression and add it to the argument | |
// array | |
args.push('return !!(' + expression + ')'); | |
// Create a new function that takes each one of the vars as a named argument | |
var fn = new F(args); | |
// Each of the values of each of the properties of the vars needs to be added to the applied arguments of the | |
// newly created function | |
for (i = 0; i < args.length; i++) { | |
vals.push(vars[args[i]]); | |
} | |
// Call the function with the supplied vars as arguments | |
return fn.apply(this, vals); | |
} | |
/* This assigns this custom syntax to the template, so it is used when parsing the bindings */ | |
listTemplate.bindingDelegate = { | |
getBinding: function (model, path/*, name, node*/) { | |
var match; | |
if ((match = expressionRE.exec(path))) { | |
return { | |
value: checkExpression(match[1], model) | |
}; | |
} | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment