Skip to content

Instantly share code, notes, and snippets.

@unscriptable
Created March 3, 2012 19:51
Show Gist options
  • Save unscriptable/1967876 to your computer and use it in GitHub Desktop.
Save unscriptable/1967876 to your computer and use it in GitHub Desktop.
wire and/or cola function to allow an arbitrary expression to be evaluated
/** MIT License (c) copyright B Cavalier & J Hann */
(function (define, globalEval) {
define(function () {
"use strict";
/**
* Creates a function that can be used to evaluate arbitrary expressions
* on a data item.
* @param options {Object}
* @returns {Function} function (value, item) {}
* @description
*/
return function createExpressionTransform (options) {
return function expressionTransform (value, item) {
try {
return globalEval.call(options.expression, value, item);
}
catch (ex) {
return ex.message;
}
}
};
});
}(
typeof define == 'function'
? define
: function (factory) { module.exports = factory(); },
function (value, item) {
var window, document;
// the only variables in scope are value, item, and any globals
// not listed in the var statement above. we have to cast to string
// because of "oddities" between `eval` and `this`.
return eval('' + this);
}
));
curl(['cola/transform/expression'], function (expression) {
console.log(expression({ expression: "value * 100 + '%'" })(0.5, {}));
console.log(expression({ expression: "new Date()" })(1330804406919, {}));
var item = { firstName: 'Ralph', lastName: 'Emerson' };
console.log(expression({ expression: "item.firstName + (item.middleName ? ' ' + item.middleName : '') + ' ' + item.lastName" })('whatevs', item));
console.log(expression({ expression: "document" })());
});
// hypothetical wirey usage:
{
bindings: {
dob: { expression: "new Date(value)" },
displayName: { expression: "item.firstName + (item.middleName ? ' ' + item.middleName : '') + ' ' + item.lastName" }
}
}
//The downside? It allows stuff like this:
"$('.allMyNodes')"; // access to other dom nodes
"dojo.date.locale.format(value)"; // access to globals
"item.otherProp = value * 100; value;"; // side-effects, non-deterministic behavior
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment