-3

so basically i have an app.js file which has a function which will pass a parameter

and i have more js files like posts.js, comment.js then i can do app.init('posts');

then i find the file, get it using getscript, but now i need to call the file.

here is my code

init:function(file){
        getfile = file;
        if($.inArray(getfile+'.js', modular_array)!==-1){
              $.getScript("js/modulars/"+getfile+'.js', function(data){
                  console.log(eval(getfile)["init"]); // this does not! why
                  //console.log(posts.init()); // this works
              });
        } else {
            console.log('not it');
        }
    }
Daniel Le
  • 199
  • 4
  • 16

1 Answers1

0

getScript loads and runs the script file automatically - you don't need to manually execute it:

init:function(file){
        getfile = file;
        if($.inArray(getfile+'.js', modular_array)!==-1){
              $.getScript("js/modulars/"+getfile+'.js');
        } else {
            console.log('not it');
        }
    }

If you do want to call some initialization function defined by the script, you can call it directly, as you discovered: posts.init()

The code eval(getfile) does not work because getfile is a filename. eval needs a string containing Javascript code.

radiaph
  • 4,001
  • 1
  • 16
  • 19