Say I have a website with a file structure like this:
index.html
main.js
modules/my-module.js
index.html contains (along with a lot of HTML):
<button id='my-btn'>My Button</button>
<script type='module' src='./main.js'></script>
main.js contains:
import { myBtn } from "./modules/my-module.js";
and modules/my-module.js contains:
const myBtn = document.querySelector("#my-btn");
myBtn.addEventListener("click", function(){
alert("Hallo from My Button");
});
export { myBtn };
Now if I click on the button I get an alert as expected.
The problem I am having is that I have some information (ie variables with values such as strings, arrays etc) in other script tags on the index.html page which I need in modules/my-module.js
I do not want to use a global variable for this because they are evil.
I thought of creating an element(s) on the index.html page with data set attributes as keys and assign values to them. The element could then be accessed from modules/my-module.js and its data set attributes would be readable. This does work when I try it but it seems a long winded way of getting access to information available on the index.html page.
It has been suggested I create a class or function returned by the module and pass data into it. The problem with that, to me, is that I am trying to keep code related to the same thing all together in the same module. If I have to pass functions out of the module to be invoked with extra data then my code base is less well organised.
Is there any other approach which would be more direct?
Related
I have the following problem, I have created a library. which its methodos
they are in separate files writeLog.js in a folder called ./lib.
and I have an index.js file that explores that folder and extracts the function
and puts the same name as the file as the function name.
example:
writeLog.js
and then I can use
let jsPackTools require('./index');
let utils = new jsPackTools();
utils.writeLog('test');
The way I use to add the methods to the classes is through the prototype.
the folder is scanned with readdirSync () and then I take the file name to
place it inside a require ().
the code is the following:
fs.readdirSync(__dirname+'/lib').forEach(modules => {
let module = modules.split('.').shift();
jsPackTools.prototype[module] =require(\`${__dirname}/lib/${module}\`);
});
Everything works perfectly fine, the problem is that when I want to access my methods through the autocomplete of any code editor. Methods they seem to be not accessible. however everything works perfectly, I can do use of functions.
The problem is that I have to know each method that I am going to use and it cannot be visualized in the completed auto of any editor.
I have tried with:
const writeLog = require('./lib/writeLog');
class jsPackTools {
get writeLog() { return writeLog.bind(this) }
}
This allows indexing perfectly. however, I don't logo do it dynamically.
The idea is that the class does not know what its methods are until the ./lib folder is scanned and all methods are extracted. This way you can add functions inderteminately and when you use them you can see.
I do not want to use transpilators, I thought of using a d.ts but it is necessary to use typeScript but the intention is to create this library without dependencies or the least possible.
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.
I have an app that uses HTML, and Coffeescript in the frontend. I recently made it possible to change the language thanks to i18next.
Now I have some buttons that change my window.userLang to the different languages, but the user has to refresh some elements of the app to see it translated.
My problem comes because I need the translations made without refreshing the HTML.
In the app, I use Craftyjs, so what I need to know is how can (if possible) from HTML file, call a function that it's defined in Craftyjs.
The function I want to call is: Crafty.scene("main").
Thanks all!
Create a global name space defined above where your scripts are included. Then in your javascript you can define the functions you need as fields on that namespace.
<script>
var MySweetWebApp = {};
</script>
<script src="..."></script>
... Inside JS file ....
MySweetWebApp.Crafty = { ... }
... From Anywhere ...
MySweetWebApp.Crafty.scene('main');
I'm using jQuery Mobile Ajax navigation feature, And I need to change a variable that is defined inside external js file, So I can't put my definition before I load that js file...
So, How to change value of a variable for external javascript file after the js file is defined?
(That external js file includes events)
So this question is not duplicate of that question.
Update
My JS File contains events, something like this: $(document).on('mousemove','#main',function() { /*something*/} );
And I need that variable. Is it possible to pass variable to that?
I have tried simply changing that variable i = 5;, but I'm getting undefined error.
Update 2
The external JS file is something for some pages that are almost same, but a little different, just one or two parameters.
And I simply want to pass the parameters to that JS file. Is it possible? How?
Let's assume http://www.example.com/external.js defines variable foo, which you want to change.
<script src="http://www.example.com/external.js"></script>
<script type="text/javascript">
foo = "my new value";
</script>
This assumes that external.js defined foo in the global scope. If it's defined in an anonymous function or similar, you won't be able to change the value.
Depending on what you're doing, you can just set the variable and it'll work. Example:
// JS file
blah = "Hello";
function doSomething() {
alert(blah);
}
// HTML file
blah = "I'm a fish";
doSomething(); // alerts "I'm a fish";
Alternatively, pass the variable as an argument to relevant functions instead of using global variables.
I need to send data in a HTML page to a script file that is loaded in that page. The simplest way i can think of is to use a global variable which is defined in the page and accessed in the script file.
We all know global state is bad, so i started thinking about the options available for passing data from HTML page to script file without using global state. I cant find (or think of) any.
I am curious whether this is possible. Any ideas?
It really depends what you're doing. In general, I wouldn't advise this methodology, but it's something to consider depending on your circumstances. For the sake of this example, I'll assume you're using jQuery (if not, replace the document.ready with whatever you want to use for onDOMReadyStateChange monitoring).
In the HTML:
<script type='text/json-data' id='some_data_set'>
{ 'foo': 'bar', 'baz': 1 }
</script>
In the JavaScript:
$(function() {
var myData = JSON.parse($('script#some_data_set').html());
// YOUR CODE GOES HERE
});
Nope. All the javascript scope starts from a global level, therefore you must have at least one global reference to your data.
Let's say you wanted to store a list of products and events:
var myGlobalData = { "products":<products>, "events":<events> };
Where <products> and <events> are two different data blocks.
If you're paranoid on global objects, you can simply delete the reference point (thus it's contents) after you finished using it, as follows:
delete window.myGlobalData;
One option is to scope your data. For example, in JS file you can define an object like:
var processor = {
function setData(o) { // do stuff
}
};
Then in your HTML you know that the data is scoped to the processor. So you can do something like:
processor.setData({someData});