Created
March 3, 2012 19:51
-
-
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
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
/** 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) { | |
// the only variables in scope are value, item, and any globals. | |
// we have to cast to string because of "oddities" between | |
// `eval` and `this`. | |
return eval('' + this); | |
} | |
)); |
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
curl(['cola/transform/expression'], function (expression) { | |
console.log(expression(0.5, {}, { expression: "value * 100 + '%'" })); | |
console.log(expression(1330804406919, {}, { expression: "new Date(value)" })); | |
var item = { firstName: 'Ralph', lastName: 'Emerson' }; | |
console.log(expression('whatevs', item, { expression: "item.firstName + (item.middleName ? ' ' + item.middleName : '') + ' ' + item.lastName" })); | |
}); | |
// hypothetical 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