From 9cabaf1ef356b0e180e20152022e136c6abd622e Mon Sep 17 00:00:00 2001 From: Valera Rozuvan Date: Fri, 4 Jan 2013 17:26:48 +0200 Subject: [PATCH] Added automatic insertion of missing "return" statement into simple function strings. Added an option to turn this feature off. --- .../js/src/graphical_slider_tool/graph.js | 29 +++++++++++++++++-- docs/source/graphical_slider_tool.rst | 6 ++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/common/lib/xmodule/xmodule/js/src/graphical_slider_tool/graph.js b/common/lib/xmodule/xmodule/js/src/graphical_slider_tool/graph.js index 678aacfe52..65511e1599 100644 --- a/common/lib/xmodule/xmodule/js/src/graphical_slider_tool/graph.js +++ b/common/lib/xmodule/xmodule/js/src/graphical_slider_tool/graph.js @@ -512,12 +512,13 @@ define('Graph', ['logme'], function (logme) { obj['@label'], obj['@point_size'], obj['@fill_area'], - obj['@bar'] + obj['@bar'], + obj['@disable_auto_return'] ); } function addFunction(funcString, color, line, dot, label, - pointSize, fillArea, bar) { + pointSize, fillArea, bar, disableAutoReturn) { var newFunctionObject, func, paramNames; // The main requirement is function string. Without it we can't @@ -532,6 +533,30 @@ define('Graph', ['logme'], function (logme) { // will break. funcString = $('
').html(funcString).text(); + // If the user did not specifically turn off this feature, + // check if the function string contains a 'return', and + // prepend a 'return ' to the string if one, or more, is not + // found. + if ( + (disableAutoReturn === undefined) || + ( + (typeof disableAutoReturn === 'string') && + (disableAutoReturn.toLowerCase() !== 'true') + ) + ) { + if (funcString.search(/return/i) === -1) { + funcString = 'return ' + funcString; + } + } else { + if (funcString.search(/return/i) === -1) { + logme( + 'ERROR: You have specified a JavaScript ' + + 'function without a "return" statemnt. Your ' + + 'function will return "undefined" by default.' + ); + } + } + // Some defaults. If no options are set for the graph, we will // make sure that at least a line is drawn for a function. newFunctionObject = { diff --git a/docs/source/graphical_slider_tool.rst b/docs/source/graphical_slider_tool.rst index 0b42519288..6334c6d77e 100644 --- a/docs/source/graphical_slider_tool.rst +++ b/docs/source/graphical_slider_tool.rst @@ -266,6 +266,12 @@ Optional parameters:: with id set in 'el_id' attribute. el_id: Id of html element, defined in 'render' section. Value of function will be rendered to content of this element. + disable_auto_return: By default, if JavaScript function string is written + without a "return" statement, one will be prepended + to it. Set to "true" to disable this functionality. + This is done so that simple functions can be defined + in an easy fashion (for example, "a", which will be + translated into "return a"). With ``output`` and ``el_id`` set together you can update html elements with function value, also function will not be plotted.