Reputation:
I have the following object:
var data = {
'buyRate': ['Buy Rate', 0.15, 'enteredData.numberOfTransactions * enteredData.buyRate',
'setupFee': ['Setup Fee', 0.00, 'enteredData.setupFee'],
'numberOfTransactions': ['# of Trans.', 10, 'enteredData.numberOfTransactions']
}
enteredData
is another object that pulls values from user inputs. Created after this object but it does exist
What I want to do is use the third position in the array as a formula to calculate a 'Total' which is displayed using a script like this (I run this after the object is created so the object keys are not undefined):
for (var key in data) {
var formula = data[key][2];
// evaluate the formula by some magic
var sum = new Function('return '+formula);
document.getElementBy(key+'Total').value = sum;
}
Because I am working in Google Sites using eval() is not an option for me. I've tried using var sum = new Function('return '+formula);
and it's not working for me. I don't get any errors. And console.log displays (no other information):
function anonymous() {
return data.numberOfTransactions * data.buyRate
}
Not sure how else to approach this problem. Would appreciate a push in the correct direction.
Upvotes: 1
Views: 349
Reputation:
The answers here helped me but after I figured out that Google Sites also don't allow creating function constructors I approached this a different way that allowed me keep the logic that I wanted.
Below the is the updated object. I simply rewrote my formula as a tiny function that I can call:
var data = {
'buyRate': ['Buy Rate', 0.15, function() {return enteredData.numberOfTransactions * enteredData.buyRate;},
'setupFee': ['Setup Fee', 0.00, function() {return enteredData.setupFee;}],
'numberOfTransactions': ['# of Trans.', 10, function() {return enteredData.numberOfTransactions;}]
}
This will run the formula every time I call it and not when the object is rendered.
My updated For...in
loop looks like this:
for (var key in data) {
var sum = data[key][2];
document.getElementBy(key+'Total').value = sum();
}
Hope this will help someone in the future.
Upvotes: 2
Reputation: 126135
If Google disallows eval
, I would guess they also disallow running user-supplied code using your Function
trick.
However, if this is not the case, you need to slightly change your function. MDN states:
Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called.
You'd therefore need to pass the correct variables, like this:
for (var key in data) {
var formula = data[key][2];
// create function
var my_func = new Function('data', 'return ' + formula);
// pass data explicitely
var sum = my_func(data);
document.getElementBy(key+'Total').value = sum;
}
Upvotes: 1