how to call js method that exist in 2 js files? - javascript

To my html file i add 2 js files
<head>
<script type="text/javascript" src="js_001.js"> </script>
<script type="text/javascript" src="js_002.js"></script>
</head>
both those js files contain method call 'func1'
How i call func1 from js_002 ?
If there is method func1 => js_001
and method func2 => js_002
When i call the func2 from my html code - i get an error about that func2 does not exist on js_001 ... why is that and how to fix it ?

Functions defined with the same name in the global scope will overwite themselves. Last definition will overwite the previous one.
So you could populate your functions inside other scopes, for example, objects:
// In js_001.js
var js_001 = {
foo : function() {
}
};
// Inside js_002.js
var js_002 = {
foo : function() {
}
};
Then you can invoke both functions by: js_001.foo(); and js_002.foo();.
Hope it helps.

As others said you can't. That is why for example using modules is a good idea when you have larger applications.
You could write your scripts in your functions in the js files inside a module that includes all functions related to some functionality like this
File js_001.js
var js_001 = (function () {
return {
foo : function () {
// code
}
};
})();
File js_002.js
var js_002 = (function () {
return {
foo : function () {
// code
}
};
})();
And call your functions like this:
onclick="js_001.foo()"
onclick="js_002.foo()"

Related

Accessing an Immediately Invoked Function Expression variable in Node.js in another file using require

File 1 - Monitor.js
var MONITOR = (function () {
// File Content
return {
doThing: function() {
doThing();
}
};
})();
File 2 - Test.js
var monitor = require('../public/js/monitor.js');
I want to access doThing() in File 2. I have tried various syntax and no luck so far.
From the frontend HTML I can simply include Monitor.js in a script tag, and call MONITOR.doThing(); without trouble but in Test.js this is proving difficult.
Any advice on how?
You have to export MONITOR so that someone else can access it with require().
Add this:
module.exports = MONITOR;
at the bottom of Monitor.js.
And, if you want the monitor.doThing() method to return some value, then you have to add a return statement to the function as in:
var MONITOR = (function () {
// File Content
return {
doThing: function() {
return "hello";
}
};
})();

jQuery.when() need to be cleared up

I have a simple .html page like this :
</html>
<head>
<script type="text/javascript" src="jquery/jquery-1.8.2.js"></script>
...
<script type="text/javascript">
var obj;
function document_load() {
obj = new mySpace.myClass();
console.log("end document load");
}
</script>
</head>
<body onload="document_load()">
...
...
</body>
</html>
myClass is a TypeScript class with this constructor :
public constructor() {
console.log("begin constructor");
(<any>$).when(
jQuery.getJSON('path/myJson1.json', function (data) {
this.obj1 = data;
console.log("here1");
}),
jQuery.getJSON('path/myJson2.json', function (data) {
this.obj2 = data;
console.log("here2");
})
).then(function () {
if (this.obj1 && this.obj2) {
console.log("here3");
this.obj3 = new myClass3();
this.obj4 = new myClass4();
console.log("everything went ok");
}
});
}
Actually the console prints this :
begin constructor
end document load
here1
here2
The reason of this behaviour is (of course) cause of asynchronous jQuery calls (or at least I guess). How can I obtain the following behaviour?
begin constructor
here1
here2
here3
everything went ok
end document load
I clarify that the jsons are taken correctly (I tried to print them and they are correct).
That's because you're not returning a promise to jQuery.when, so the callback gets called and this.obj1 && this.obj2 are both null.
A better way to do this would be:
(<any>$).when(
jQuery.getJSON('path/myJson1.json'),
jQuery.getJSON('path/myJson2.json')
)
.then(function (obj1, obj2) {
// Code
});
Replace all functions with arrow functions (=>). This will ensure that "this" points to the correct thing in all function bodies.
More : https://www.youtube.com/watch?v=tvocUcbCupA

probably moronic js syntax error. Object is null

var fbToggle = document.getElementById("fbToggle");
and later in the script
fbToggle.addEventListener("click", toggle("fbContainer"));
Console tells me that fbToggle is NULL
This is in the document though.
<input type="checkbox" id="fbToggle">
I wasnt using eventListener before, so maybe there is a special order of declaration i'm missing ?
EDIT :
entire js :
function toggle(target) {
var obj = document.getElementById(target);
display = obj.style.display;
if (display == "none") {display = "block"}
else {display = "none"}
}
function init() {
var fbToggle = document.getElementById("fbToggle");
var twitToggle = document.getElementById("twitToggle");
var pinToggle = document.getElementById("pinToggle");
console.log(fbToggle); // NULL
fbToggle.addEventListener("click", toggle("fbContainer"));
twitToggle.addEventListener("click", toggle("twitContainer"));
pinToggle.addEventListener("click", toggle("pinContainer"));
}
window.onload = init();
HTML is way too long.but JS is in head, called from external file. Also i'm not in quirk mode.
It is not clear where "later in the script" is. If it is in different scope definitely it is not going to work. Suggesting you to keep everything in a global object if possible so that you can access from different places in the script.
window.globals = {};
window.globals.fbToggle = document.getElementById("fbToggle");
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
http://jsfiddle.net/ST938/
Another point is addEventListener expects a function or function idenitifier, NOT a function call.
addEventListener("click", toggle("fbContainer")); // wrong
addEventListener("click", toggle); // correct
So if you want to pass a parameter
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
In JavaScript, putting brackets after a function name causes it to be called. If you want to reference a function without calling it you must not put brackets after the name:
window.onload = init(); // this calls init() immediately
window.onload = init; // this correctly stores init in window.onload
The same applies to toggle(). If you need to pre-specify some of the arguments you can wrap it in an anonymous function:
fbToggle.addEventListener("click", function() { toggle("fbContainer"); });
or you can use bind:
fbToggle.addEventListener("click", toggle.bind(null, "fbContainer"));

Overwrite object methods / functions

I have the original.js file, but I want to change some things in it. I can't modify original.js, but I can add another better.js file so that I could overwrite some functions of original.js
original.js contains:
MyHandler = {
data:{},
var1:false;
handlers:{},
init:function(handlers){
function1();
function2();
}
function1:function()
{
// function1 code that needs to be replaced
};
}
$(document).ready(function ()
{
///...some code
MyHandler.init();
}
I want to rewrite function1() with new content.
What should I put within better.js file?
P.S. I know better.js should follow after original.js.
I've tried to put the code below to better.js, but it doesn't work (seems like none of function1 work then)
MyHandler = {
function1:function()
{
// new code
};
}
What am I doing wrong?
Just do like this:
if (!MyHandler) { MyHandler = {};}
MyHandler.function1 = function() { ... };
Or you can use jQuery $.extend api method.

How to mangage javascript files and encapsulate JavaScript/jQuery functions

I need to write & manage a lot of JavaScript code for current project.
I separate them into multiple .js files mainly based on module.
So, now i have for example:
Map.js // deal with google map issue
Common.js // common functions that will share by all modules
User.js // user module js code
Geofence.js // geofence module js code
etc.....
For example, inside my User.js file
what if i want to declare a function that only used inside the User.js file, not accessible by outside. what can i do?
var User = {};
User.registerModule = function () {
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers();
// ...
});
}
function getAllUsers(){ // how to hide this function
// get
return users;
}
So, in my home page, i only need to coordinate with multiple .js files. Access what allows to access.
$(document).ready(function (data) {
GoogleMap.initialiseGoogleMap();
Common.refreshRightScrollbar();
User.registerModule();
// ...
});
It is my first time to write js and not enough time to study a whole book. So, please, in your opinion, is this structure ok with many js code? and how to hide functions that i dont want outside to access?
to hide that function you have different possibilities
just enclose your code in an immediate self-executed anonymous function
var User = {}; // this should not be enclosed too
(function() {
User.registerModule = function () {
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers();
// ...
});
}
function getAllUsers(){ // how to hide this function
// get
return users;
}
})();
enclose that function inside User.registerModule function
User.registerModule = function () {
function getAllUsers() { ... }
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers();
// ...
});
}
Place this function inside the scope:
User.registerModule = function () {
function getAllUsers(){ // how to hide this function
// get
return users;
}
$('#user').click(function () {
Common.showLeftScrollbar();
getAllUsers(); // returns users
// ...
});
}
And it will be private.
Now if you try to call this function outside it will be undefined:
getAllUsers(); // undefined.

Categories

Resources