Can I tell Javascript to call a method from another JS file? - javascript

In AppMenu.js,
AppMenu = function()
{
var scope = this;
}
Also noted:
Star.Bus.addEvent("AppMenu_StatSheet");
Star.Bus.on("AppMenu_StatSheet", scope.AppMenu_StatSheet, scope);
scope.registerApp("Exit Game", "AppMenu/images/exit_button.png", "AppMenu_exit", "");
Further down is a method
scope.AppMenu_StatSheet = function()
{
showStats();
}
I moved the location of the showStats() method to another js file, and I want the method to send its call there instead of where it originally was going. In Javascript, can I tell the program where to look to call showStats()?
EDIT Curiously, there is no AppMenu.html. I now believe that all of the html is dealt with by a main HTML file in the above folder.

If you include both Javascript files in your PHP/HTML page, the compiler automatically uses your showStats() function, even when it is called from file1.js and the actual function is located in file2.js.

As long as you include both files in your HTML page you'll be fine. Maybe load the file with showStats() before the other one.

Related

How to call a function in an html file from another html file

I'm trying to call a function from my html: tasks-div-upload.html to my other html: task-tareas-actualizadas.html.
I'm including my scripts on the script tags of the html files
I tried to call the function like this
First of all this is the html that calls the function: tasks-divs-upload.html
and the function is in task-tareas-actualizadas.html
I tried to call the function like i do in java that is
writing the class and then the function, for example: people.countPeople(5);
In this case, there are not classes because its an html file so what can I do?
//tasks-divs-upload.html
function contadorTareas(){
for(var x = 0; x < divs; x++){
var numeroTareas = x;
}
prueba(numeroTareas); // <---------
}
//task-tareas-actualizadas.html
function prueba(numero){
console.log(numero);
}
Console shows this error "Uncaught ReferenceError: prueba is not defined"
This CAN be done but is mostly a bad idea and is not very common and has some specific requirements. It is best it NOT be done unless the user is aware of the interaction.
IF your task-tareas-actualizadas.html opens tasks-divs-upload.html in a new window then tasks-divs-upload.html can call window.opener.prueba() BUT, if the first window gets closed, it will not be there and they must both be of the same origin.
This interaction can also go the other way if the parent keeps a reference to the child window.
Better to create a JavaScript file say "myfunctions.js" that includes the functions you wish to use and include it in both pages UNLESS for some reason you need/want the pages to interact - say the child page alters the parent page DOM or some such.
Reference https://developer.mozilla.org/en-US/docs/Web/API/Window/opener
and https://developer.mozilla.org/en-US/docs/Web/API/Window/open
Well scripts in HTML are JavaScript code. They need to be either defined in separate .js files or included in html using <script> tags.
It is not possible to define a JavaScript function in a html file and then use it in another html file. You need to define the function is a separate JavaScript file and then include this file in the html page.
You may also use JavaScript modules which are natively supported by modern browsers.

How do I add a personal script to an existing node.js library?

I have a local copy of the hls.js library and I need to include a personal script with custom functions in it.
How do I go about adding a new script to the library and how do I use the function written in the new script?
Let's say that I want to add a script called hello.js that contains a function that logs "Hello World".
When I call that function in my main.js I need it to execute.
Any ideas on how to do this?
Currently, I'm getting an error that the function is not defined.
I placed the hello.js script in the src folder of the library but this (as expected) doesn't seem to work.
It should be possible to add functions to the exported hls.js object.
Your custom-script.js:
var hls = require('hls.js')
hls.customFunc1 = function () {
}
hls.customFunc2 = function () {
}
on main.js:
require('custom-script')
// your code follows
Any other code would be able to use the custom functions by just require'ing hls.js.

files not loading correctly

Good afternoon everyone! I have searched the web to resolve this problem and tried to implement what I could see as the solution, but I still occasionally run into problems...
The project is modular in design with each module having a .html, .js, and .css file. When loading a module, those associated files are checked for and if they already exist in the DOM (e.g. the module has been opened at least once already), then there are no problems. If the files aren't already loaded (e.g. the module hasn't been loaded yet), then occasionally I run into a problem where a javascript function is called, but the external .js file hasn't been loaded yet. Here's the below function responsible for handling this:
function loadFile(sType,sURI,sCallback) {
// sType the type of file to load: link, script
// sURI the URI of the file to load
// sCallback the code to execute after successfully loading the file
var ref = document.createElement(sType);
if (sType == 'script') {
ref.setAttribute("type","text/javascript");
ref.setAttribute("src",sURI);
} else if (sType == 'link') {
ref.setAttribute("rel","stylesheet");
ref.setAttribute("type","text/css");
ref.setAttribute("href",sURI);
}
ref.async = true;
ref.onreadystatechange = ref.onload = function() {
var state = ref.readyState;
if (! sCallback.done && (! state || /loaded|complete/.test(state))) {
sCallback.done = true;
if (typeof(sCallback) === 'function') {
callback();
} else {
eval(sCallback);
}
}
};
document.getElementsByTagName('head')[0].appendChild(ref);
}
There are several other SO articles that were used for the above function:
Dynamically load external javascript file, and wait for it to load - without using JQuery
Javascript check if function exists
So the above function will be called like:
loadFile('link',"module.css?cache=0", $("#divModule").hide().load("module.php?action=init").fadeIn('slow'));
loadFile('script',"module.js?cache=0", "initModule('req')");
The first call will load the .html file contents (via the module.php call) for the module after the .css file has downloaded. The second call will call the modules js init function after the .js file has downloaded.
It doesn't appear to have any issues with the .css file, but sometimes the module will not load correctly meaning that the layout is rendered correctly, but no values populate (which is what happens with the modules js init function). If I check the 'Web console' in FF, there aren't any errors that are thrown. Any thoughts?
Thanks,
Dave
Hard to say for me w/o seeing what's happening in that module.php code, but it looks to me like your first one at least is firing immediately, rather than as a callback. Unless I'm missing something, the callback should be a function, while right now you're actually executing the jquery hide/load stuff right when you call loadfile. You might want to wrap it in a function.

In my asp.net-mvc file, how can I move my javascript to a seperate js file?

I have a bunch of javascript inside my view and its getting quite large so I want to move it to a separate js file. The one issue I have is that I have this line:
var tags = <%= new JavaScriptSerializer().Serialize(Model.Tags) %>;
which I obviously can't just copy over since it has the server side asp.net-mvc tags. What is the recommended way to deal with that:
Keep this one function inside the aspx page and have the javascript from the seperate js file call that function?
Other??
What you could do is have a JavaScript object contain all the information you get from the controller and pass it through a javascript function which is located in the external javascript file. You can also pass other information through the options variable.
Example:
var options = {
tags: <%= new JavaScriptSerializer().Serialize(Model.Tags) %>
};
initPage(options);
Usage:
function initPage(options) {
console.log(options.tags);
}
This depends a lot on the way you want to use it and the level of repeating.
Some thoughts:
The tags are static. Then I guess then don't really need to be in the model. So you can move them into a new Controller action which outputs the scipt. You can call this action in the <script> part of your view.
The tags are changing very frequently (maybe even at every page load). Then there is no gain in moving this in a separate script file.
If you set up your javascript file with proper closures, you can expose a property (or better yet, a parameter to the object/method) with which to pass that information along when you call that function.
Your Javascript would need to be something like this:
var JsFile = (function() {
var tags;
// list all of your methods here.
return {
var setTags = function(_tags) {
tags = _tags;
}
};
})();

Calling a JavaScript function outside of the js file

I have problems with calling a JavaScript function (which is inside of an object, in it's own .js file) from an other HTML page. In the code exsample I'll just use a simple Hello World function.
//.js file
window.addEvent('domready',function(){
var Site = {
//Here I have like three other functions
//This function I want to detect the browser version. I use MooTools for this
detectBrowser : function(){
if(Browser.ie){
//Then what ever content goes here
}
}
}
//I execute the other three functions here because they need to be called on every page
Site.dropdownmenu();
Site.accordion();
Site.lightbox();
});
I'm working with MooTools so I have wraped everything inside of the domready function.
Now, I want this cetect function to execute only at one page. I have tried somethink like this:
//In the HTML file between two script tags:
Site.alert();
That does'nt work. Any ideas?
If I execute it in the .js file it works fine. But I don't want it to execute at every page.
If you declare a variable with var in a function, the variable is local to that function and inaccessible from outside that function. To make it explicitly global, declare it as a property of window:
window.addEvent('domready',function(){
window.Site = ...
This isn't necessary for the code to work, it just makes it explicit for programmers that might read your code that Site is a global.
External Javascript files just execute code; the code doesn't know where it's coming from.
As long as your code runs after the external JS file, it will work fine.

Categories