0

I have multiple javascript files, and userIsLoggedin function is exist in all of them, i want after user log in, userIsLoggedin function call in all javascript files.

there is my code:

login.js

...
userIsLoggedin();
...

file_1.js

...
function userIsLoggedin(){  ...  }
...

file_2.js

...
function userIsLoggedin(){  ...  }
...

file_3.js

...
function userIsLoggedin(){  ...  }
...

...

file_n.js

...
function userIsLoggedin(){  ...  }
...

but it call only userIsLoggedin function in file_n.js file.

MHS
  • 881
  • 1
  • 13
  • 30
  • 1
    Its not possible to call all function with single line call, the behave you getting is correct. for your task, you should provide all function with different namespaces and then call all function in 1 common single function and in your main script that global/main function calling will call all the function. for namespace, ref link http://stackoverflow.com/questions/881515/how-do-i-declare-a-namespace-in-javascript – Rupal Javiya Jul 27 '16 at 12:31

2 Answers2

1

In your each js, define namespace like

var login = {
    userIsLoggedin: function() {
    }
};

Here login is namespace name

Copy this same script in all js files with changing namespace name (ie. replace login with file_1, file_2, file_3... likewise

Then call all login function like

login.userIsLoggedin();
file_1.userIsLoggedin();
file_2.userIsLoggedin();
file_3.userIsLoggedin();
.
.
.
file_n.userIsLoggedin();

You can create 1 global function where you can add all these calls.

Rupal Javiya
  • 591
  • 5
  • 14
0

If I am getting this right looking at your example, JS is only allowing the last file loaded's function declaration to be valid. What will happen is each file will get evaluated and the next will overwrite the declaration. So, if you were to look at what functions would be available in your namespace, only the last one declared would be there.

If you need it to fire from each file, you will need to organize your code a bit differently. Something like:

login.js

var obj1 = require('obj1.js');
var obj2 = require('obj2.js');
...
var objN = require('objN.js');

(function userIsLoggedin(){
  obj1.userIsLoggedIn();
  obj2.userIsLoggedIn();
  ...
  objN.userIsLoggedIn();
})();

obj1.js

module.export = {
  userIsLoggedIn: function(){
    ......
  }
}

obj1.js

module.export = {
  userIsLoggedIn: function(){
    ......
  }
}

objN.js

module.export = {
  userIsLoggedIn: function(){
    ......
  }
}

Is that what you are looking for?

tunagami
  • 51
  • 2