Hello!
I have a MEN stack application that needs to retrieve functions from the server to run in the client. So far I have been passing in an array of functions, and parsing them. Everything is technically working but I’m having to repeat the same for loop in multiple functions.
APP.JS
[CODE]
app.get(“/logictest”, function(request, response){
response.send(myFuncs);
})
var myFunc = “function test1() {alert(‘test 1’);}”;
var myFunc2 = “function test2() {alert(‘test 2’);}”;
var myFuncs = [
myFunc,
myFunc2
];
public js
[CODE]
// CALL OUR TEST FUNCTION FROM THE GAME LOGIC
var callTest1 = function(){
[COLOR=”#FF0000″] for (var i=0; i<theLogic.length;i++){
eval(theLogic[i]);
}[/COLOR]
test1();
}
// CALL OUR SECOND TEST FUNCTION FROM THE GAME LOGIC
var callTest2 = function(){
[COLOR=”#FF0000″] for (var i=0; i<theLogic.length;i++){
eval(theLogic[i]);
}[/COLOR]
test2();
}
$(document).ready(function() {
// AJAX REQUEST FOR GAME LOGIC
console.log(“requesting logic from server”);
$.ajax({
url: ‘https://thesite/logictest’,
type: ‘GET’,
success: function (data) {
console.log(‘success’, data);
// CREATE LOGIC ARRAY
theLogic =[];
// POPULATE THE LOGIC ARRAY WITH FUNCTIONS
for (var i = 0; i < data.length; i++){
console.log(‘Converting : ‘ + data[i]);
theLogic[i] = data[i];
var jsonVal = JSON.stringify(theLogic[i]);
theLogic[i] = $.parseJSON(jsonVal);
console.log(theLogic[i] + ” available to front end”);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(‘error’, errorThrown);
}
});
});
Using
[CODE]
[B] for (var i=0; i<theLogic.length;i++){
eval(theLogic[i]);
}[/B]
prior to calling the function is not only being used to make it available, but all of the other functions as well so that they can be accessed by the current function if needed.
This solution is technically working for me but there must be a way that I can evaluate everything in the theLogic array one time at the start and use that information to simply make test1() and test2() available everywhere on the page without having evaluate every item in the array every time I need to use a function.
Maybe I missed something, and there’s a better way to go about all of this in general. any advice would be appreciated!