How can I call a concrete Coffeecript function from html - javascript

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');

Related

How to make JavaScript variables available to ES6 modules

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?

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 to use external javascript script for variables?

I have a very long script which included many variable definitions. I am using Openlayers.js to create a webmapping application which contains about 100 layers. Each layer has to be defined as a variable and bloats the script.
I thought I could simply create a layer.js file which contains the layer definitions and reference it before the main app.js in the html start page, but this is not working.
For reference,my javascript can be seen here: http://maps.zgb.de/geoportal/app.js
The first half-page is just defining variables.
Could anyone tell me what the best-practice is in this situation?
cheers
This might be of some help http://jacklmoore.com/notes/setcountdown/
They use images in that link but im sure the same would apply to pulling in script tags.
Alternatively you could have something like this
----- HTML Page -----
function loadApp() {
document.write('<script type="text/javascript" src="path/to/app.js"></script>');
}
---- Layers.js -----
var xyz = abc;
....
// right at the bpottom
loadApp();

Passing Querystring style parameters into Javascript file

Not sure if this is possible or even if I should do it, but I think it's quite interesting.
I have a javascript file which I'm referencing in a flat HTML page. I'd like to pass in a parameter or two via the path to the script. Like this;
<script src="/scripts/myJavascriptFile.js?config1=true" type="text/javascript"></script>
Not really sure if it can work but it would make my solution a little easier for others to take my script and implement (arguable).
Cheers,
Mike
I don't think that passing in variables via the src attribute is possible out of the box without some extra coding on your part (there is an article here if you are interested!). You could do the following though, which should provide the same functionality as you are looking for:
Define your "config" variables in a single script block on your HTML page:
<script type="text/javascript">
var config1 = true;
</script>
Reference your external JS file in a second script block:
<script src="/scripts/myJavascriptFile.js" type="text/javascript"></script>
Add this code to your external JS file to reference the "local" variable in your HTML:
var conf1 = window.config1;
if (conf1) {
// Do stuff
}
This is a variation on Matt's answer. I have a similar case where I need a jQuery file to use a value that is generated in the HTML (by Razor in this case). I write the value to a meta tag, generated as it is from the controller:
<meta name="sessionId" content="#ViewBag.SessionId">
and then read it in the jQuery file:
var sessionId = $("meta[name=sessionId]").attr("content");
It's not quite the same as passing it in by querystring, but useful if that information is considered "meta-information" of the HTML page.

AJAX & ASP.net, Referencing server controls in external file

I've got some JavaScript in an ASP.NET page that looks like this:
var list = $get('<%=Topics.ClientID %>');
I have many functions written now where this syntax is used, and I would like to centralize my JavaScript and move this into an external JavaScript file. This breaks however, since 'Topics' cannot be found.
What is the best strategy for getting this to work? I assume I should pass the control/control information as a parameter to the function, but I can't seem to get the syntax to work. Any suggestions?
It's a common problem for ASP.NET JS development. As for me, I'm using same approach each time and it looks fine.
I'm used to OOP in Javascript, so most my JS external files look like:
function CouponManager()
{
}
And in .aspx code i do:
<script language="javascript">
var couponManager = new CouponManager();
</script>
If I need to pass some parameters I change the declaration of class to:
function CouponManager(params)
{
// .. stuff here
this.initialize = function(initParams)
{
// .. accessing initParams variable for server control IDs
};
this.initialize(params);
}
And from .aspx code I do the following:
<script language="javascript">
var couponManager = new CouponManager
({
txtCouponNameId = '<%= txtCouponName.ClientID %>',
txtCouponDescriptionId = '<%= txtCouponDescription.ClientID %>'
});
</script>
This approach allows me to separate JS from .aspx page and have all server control dependencies in a single tag.
You should create a javascript method from inside the usercontol which returns the client side element. Then in your other page/control, just access that method
In User Control
<script language="javascript">
function GetTopics() {
return = $get('<%=Topics.ClientID %>');
}
</script>
In other page/control
<script language="javascript">
var list = GetTopics();
</script>
Edit - The problem you are facing is you need Topics.ClientID where it doesn't exist. So the only real way to bridge that gap is to put it in a common place. If you really don't want to do that, you can try and select your element by some other criteria. If you are using jQuery, you could mark an element with a class of Topics then find it with $(".Topics").
if you know that you only have one server control called "Topics" per page, and you use naming conventions you can inherit from whatever the control Topics is (maybe it's a HiddenField? you don't specify) and override its ClientId getter to return its server id like this:
http://andreascode.wordpress.com/2009/04/27/tiny-drips-of-aspnet-juice/
then you can know in your javascript files that there will be a hidden field in the page with the id set to "Topics" and use that directly.
depending on your domain/situation this could either save you a lot of time or screw you over big time.

Categories