How expose javascript variable with Rails 6? - javascript

I have in javascipt/pack a home.js file
var hello = "hello"
window.hello2 = "hello"
But, after loading the view associated (home.html.erb), in the javascript console of my navigator for these variables I get Uncaught ReferenceError: hello is not defined or undefined

var hello = "Hello" - When you type > hello in console, this will not work because of a concept called Closure in Javascript. I found this article helpful.
window.hello2 = "Hello" -> You are assigning a global variable. When you type > window.hello2 in console it will give the output, but just > hello2 won't work and it gives ReferenceError.
window.hello2 is available to all your JS code, it is global.
However, it's not recommended to use global variables, use vars in respective functions.
Also, you didn't mention that how you're using your pack/home.js file.
If you include <%= javascript_pack_tag 'home' %> in app/views/layouts/application.html.erb, then your JS code will run in every controller/view(not just in Home controller.)
If you include <%= javascript_pack_tag 'home' %> in app/views/home/index.html.erb, then your JS code will run in only in home#index action - but it triggers refresh.

Related

Getting variable reference errors after implementing es6 modules

I'm trying to clean up my code and implement es6 modules for the first time. I have created three module files and am using the import/export keyword where necessary and have specified type="module" in index.html.
The problem is everything functions correctly except all the global variables are undefined in my main file and now I get Reference Errors: Variable not defined if I try to console.log(variable)in the console. Confusing me further is if I place the same console.log(variable) inside an IIFE within the file it correctly displays the variable value with no Reference Error.
For example:
<script type="module">
let foo = "some text";
(function() {
console.log(foo)
}()); // prints "some text"
console.log(foo); // prints Reference Error: foo not defined
</script>
Are there special rules for how global variables are handled in es6 modules? I'm just really confused because the everything else works properly and all I changed was splitting my file using es6 modules and running a local server (because of CORS error from using module pattern).
It appears my issue was a misunderstanding of how the console works and that it doesn't have access to a variable within a module file unless it is made global by attaching it to window.
For example, this now allows me to access the variable in question:
let foo = "some text";
window.foo = foo;
console.log(foo); // now prints "some text" in the console instead of Reference Error
Related answers:
How to access functions defined in es6 module in a browsers javascript console
What is the correct way to define global variable in ES6 modules?

ReactJS - External JS Function "is not a function"

In short, I'm trying to call an external JS function which my 3rd party required me to include, in order to use their API, but doesn't work as it supposed to.
From what I've read, I am supposed to use, for example, window.extFn() after including the external JS in my index.html which contains the extFn() like so
<script src="https://example.com/external.js"></script> <-- actually not like this, see update 2 as I imported the library locally
...and supposed to use it like how it was answered here: Call external Javascript function from react components regardless of whether the said function is inside a file or simply defined on index.html <script> section. This had worked on the JS file I created for testing this.
//File: test.js
function test() {
return "Hello";
}
...imported the JS file with script tag like usual, and using console.log(window.test()) in my React Component's render() returned Hello.
I tried moving the import to HTML head from body and vice-versa but the error I'm still getting is:
TypeError: window.extFn is not a function
QuickCheckout.render
....
22 | }
23 |
24 | render() {
> 25 | window.extFn({
26 |
View compiled
▶ 20 stack frames were collapsed.
And when I look into my browser console, for some reason I have (which seems to be the key problem)
Uncaught SyntaxError: Unexpected token < external.js:1
Tried console.log(window.extFn) and it returns undefined
So I think it might be possible that the said JS is the problem itself, but I'm at my wit's end with this. Meanwhile I had emailed my 3rd party support team, does anyone have any advice on this? Thank you very much.
UPDATE: Now my test.js file above, which had worked in my experiment, produces the Unexpected token < error as well in my console...
UPDATE 2: I apologize for your problems. But I actually imported the JS from local source due to having to port their library as they had jQuery 2 instead of 3.
<script src="assets/js/external.js"></script>
And to my dumbness, i forgot the trailing /. Thank you for your help.
It seems that the path of external.js is wrong, which returns a html file instead of js file
you can check what the request of external.js returns at the "network" tab in chrome dev-tool
At the begining of file, before the class definition, please add
let extFn = window.extFn
then inside of component,you can use it.
extFn()//call inside component

Undefined jscript in javascript

I have created an ASP.Net application. I am using a javascript which is written in a separate file. I am using Var myvariableName ={} in javascript file.
I have included this file in MasterPage and accessing myvariableName in my aspx page.
This is working fine in Google Chrome, however, in IE 8 an unhandled exception is thrown as
myvariableName is undefined.
the error shows as;
0x800a1391 - Microsoft JScript runtime error: 'Common' is undefined
where Common is my javascript variable.
Please assist me in resolving this issue.
You're probably accessing the variable before your external script is executed.
Be sure to access your variable as soon as the document is fully loaded (i.e. $(document).ready(function(){...}); if you use jQuery) or try to find out the real execution order with some alert (that shouldn't be browser-depentent, by the way!).
If your code is already in a document.load or $(document).ready(function) you can always
handle the variable before acessing it via
if (typeof myvariableName !== "undefined") {
// do stuff
}
Some times in IE shit happens and window.load gets screwed specially when async calls are in place.
You are probably getting this error due to a missing semicolon. Change the code to this:
var myvariableName = {};
In your asp page, where you access your custom variable, wrap your code with:
var myvariableName = {};
window.onload = function(){
// your code here where you're accessing the variable
};

Embed backbone response into underscore template within Rails?

I'm using backbone.js for a rails project I've got on the side. I'm embedding templates in the rails views using something like:
<script type="text/template" id="this-is-the-id">
... template goes here ...
... the line below this is where my error's coming from ...
<%% _(<%= aNumber %>.times(function(){ console.log('hi'); });) %>
</script>
I'm getting the error Uncaught SyntaxError: Unexpected token <. If I replace <%= aNumber %> with an integer, it works as expected. Also, if I console.log(<%%= aNumber %>), it logs the correct number.
Does anybody know how I can accomplish something like this? I know that's kind of a sloppy way to organize my code, but this is just a quick little hack I'm putting together.
Thanks!
Turns out I didn't need to wrap aNumber within the escaping <%%= and %>, and that fixed it for me.

javascript global variables visibility

I'm using a global variable in javascript, declared in a script tag outside any function:
<script type="text/javascript">
var prov_status_dict={};
....
</script>
Later on in a javascript method I'm using the variable normally.
temp=prov_status_dict[current_as_id];
I'm having issues with it on opera and ie, while on firefox it works. This is what opera's error console reports:
JavaScript - http://localhost:8000/input/
Event thread: click
Error:
name: ReferenceError
message: Statement on line 62: Undefined variable: prov_status_dict
stacktrace: n/a; see opera:config#UserPrefs|Exceptions Have Stacktrace
I've noticed that the problem is with global variables in general. I tryed moving some into hidden fields, but the same error pops up on the next use of a global var.
Help?
I usually access my globals through the window object so that I always have a point of reference
window.MyVariables = {};
window.MyVariables.prov_status_dict = {};
Give this a try, it might resolve your problem.
Try to avoid using global variables, see http://yuiblog.com/blog/2006/06/01/global-domination

Categories

Resources