I have set a variable in one of my javascript files and i want to access that variable in an html file . How do i do the same?
here us my javascript code(file name is JSUI.js):
JSUI = function () {
this.glistName = null;
this.renderUI = function(list) {
this.glistName = list.listName;
window.location="page2.html";
};
};
var gJSUI = new JSUI();
page2.html:
<body>
<script src="js/JSUI.js"></script>
ListName: <input type="text" id="listName"></input>
</body>
<script type="text/javascript">
if(document.readyState="complete"){
document.getElementById("listName").value = gJSUI.glistName;
}
</script>
Basically page2.html gets loaded when renderUI method of JSUI.js is called and i want to populate a textbox present in page2.html with a variable defined in JSUI.js file .How do I achieve the same?
you have actually created a class but there are some mistakes and the most important : you don't initialize the class itself.
Try this:
JSUI = function () {
this.glistName = null;
this.renderUI = function(list) {
this.glistName = list.listName;
window.location="page2.html";
};
};
And in you page:
if(document.readyState="complete") {
var myobject = new JSUI();
document.getElementById("listName").value = myobject.glistName;
}
There are different methods to achieve the desired result:
1) Set the variable to the global Window object;
2) Use a modular pattern where you export the variable in one js file, and import it in the other (which I'd use). Use AMD (requirejs), commonjs, ES6 modules, ... ;
3) Use the localstorage to store state;
4) Use the DOM to store state;
5) Keep state at the server and use dehydrate to extract state into JS objects to different components when the js gets loaded;
6) Use ajax to get state from the server when the page is loaded and dispatch the state to different components that need it on app bootstrap;
Related
I have a file that exports some functions in a Vuejs project, and I need to use them also in an external environment .. inComponent I know which function I should use by identifying by name and comparing with a .JSON file this works cool in the environment of development but when I build the project the functions are renamed as in the image:
Is there any other reference in these functions where I can identify them other than by name? any reference in memory I don't know? Thank you!
You can define a unique value in the body of each function and then when you have a reference to one of the functions in your list you can call the toString() method of the function reference to get the source code of the function - and then check whether the desired unique value is present in the code.
Something like this:
const myFunc1 = function (...)
{
const uniqueIdent = 'zvjbesvfexrxe3cg4g3ewumkaj2hrz9m';
.....
}
const myFunc2 = function (...)
{
const uniqueIdent = 'y4wxfjedrr3mh6k5ju2gcff6wxafjcz5';
.....
}
// make the list of functions globally available
window.myFuncList = { myFunc1, myFunc2 };
// try to find the uglyfied name of Func2
var key;
var realNameFunc2;
for (key in window.myFuncList)
{
if (window.myFuncList[key].toString().indexOf('y4wxfjedrr3mh6k5ju2gcff6wxafjcz5') !== -1)
{
realNameFunc2 = key;
break;
}
}
// you can now invoke your function as realNameFunc2(...)
I am implementing a credit card payment form in ReactJS using a 3rd party bank JS which works using iframes.
The logic is I load bank's javascript in my page, something like this:
<script src="https://my-bank.com/super-secure-script.js"></script>
Then I collect user's CC data in my ReactJS component, then call a function like this:
window.Bank.SendPayment(CC, this.paymentCompletedCallback);
...
paymentCompletedCallback = (result) => {
// process payment result here, inside my component
}
The problem is: the code inside super-secure-script.js cannot find the callback this.paymentCompletedCallback, because it is inside inside my component.
The question is: how can I pass to an external script a reference to a react object function?
You can attach the function to the window object:
const Component = () => {
const func = () => {
console.log('do something');
};
window.func = func;
};
this.paymentCompletedCallback.bind(this) may solve the problem.
Here is another example of when binding is necessary, hope that makes it more clear to you:
var Button = function(content) {
this.content = content;
};
Button.prototype.click = function() {
console.log(this.content + ' clicked');
};
var myButton = new Button('OK');
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the global object
var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
Let's say I have a library module that looks like this:
module.exports = {
increment: function() {
count++;
}
}
And I'd like to use it in a dynamically generated script that looks like this:
(function() { lib.increment(); })();
by passing it in a sandbox:
var sandbox = {
count: 1
lib: require('./lib')
}
var script = new vm.Script('(function() { lib.increment() })();');
script.runInNewContext(sandbox);
The obvious problem I run into is that I on the one hand can't require "lib" because "count" is not defined in lib.js ; on the other hand if I define var count above the exports of the "lib.js" file, this new count variable will be affected instead of the one in the sandbox.
Here are the constraints that I would like to respect:
Use vm and not a eval() nor a require() on a generated file
Have "lib" defined in a external file
No modification of the automatically generated script, so no use of lib.increment.apply(context) or similar
The only solutions I've found so far is to prepend the lib functions in the generated script as a string, or to define them directly on the sandbox object, which I find to be a less desirable option.
There doesn't seem to be any way of passing a context of variables on the require call.
One way of accomplishing this is have your lib module be a function that takes in a context then returns the correct interface.
lib.js
module.exports = function(context) {
var count = context.count;
return {
increment: function() {
count++;
}
};
};
main.js
var sandbox = {
count: 1
};
sandbox.lib = require('./lib')(sandbox);
var script = new vm.Script('(function() { lib.increment() })();');
script.runInNewContext(sandbox);
I declare a instance related dictionary.
Template.newMessage.onCreated(function () {
var self = this;
self.dict = new ReactiveDict('namedDic');
});
And access it via Template.instance().dict.get() in helpers and events.
However, autoform nests another template somewhere so my code to access this dict, no longer works:
AutoForm.hooks({
serverCall: {
before: {
method: function (insert, update, current) {
insert.foo = Template.instance().dict.get('foo'); <-- fails
Meteor.call('serverCall', insert);
return true;
}
}
}
});
The doco doesn't seem to mention any way to access the parent template and I don't want to start guessing how many levels of parents it is.
If it makes any difference, my markup looks like this:
+quickForm id='newMessage' schema='Schema.CustomMessage' type='method' meteormethod='serverCall'
This is a bit of a A->B problem, what I want to do is just have autoform generate and validate a few fields, then I can insert some hidden values as part of a helper/event/hook before sending it off to the server.
I'm sure it is not a best approach, but I got it works by setting external variable in the same file scope.
Example:
var myNewMessageTemplate = null;
Template.newMessage.onCreated(function () {
var self = this;
self.dict = new ReactiveDict('namedDic');
myNewMessageTemplate = self;
});
AutoForm.hooks({
serverCall: {
before: {
method: function (insert, update, current) {
insert.foo = myNewMessageTemplate.dict.get('foo'); <-- fails
Meteor.call('serverCall', insert);
return true;
}
}
}
});
What you need to be insure, that hooks and onCreate are in the same file, to be in the same scope.
I've done this in the past like so:
Define a helper to retrieve the ReactiveDict
Template.newMessage.helpers({
foo : function () {
return Template.instance().dict.get('foo');
}
});
Then, I include that helper somewhere in my template. Use class="hidden" if you don't want the user to see it.
<input type="text" class="hidden" value="{{foo}}" data-schema-key="foo" name="foo">
When quickForm submits, I believe it looks for all inputs with a data-schema-key attribute defined (or possibly it looks at the name, you can define both just to be certain.
Using this method, you should not need to define any hooks.
<script src="http://domain.com/source1.js"></script>
<script src="http://domain.com/source2.js"></script>
source1.js
var PICTURE_PATH = "";
var PICTURE_ROOT = base_url+"YOUTAILOR_files/";
var PROGRAM = parseInt("1");
source2.js
if(PROGRAM==3 || PROGRAM==4 || PROGRAM==5)
{
}
I could not access value of program in source2.js..
When you declare var source1Var outside a function you are actually creating a variable on the window object. So you should just be able to access it from source2.js. Just make sure source1.js is before source2.js in the script tags...
If however you're declaring it within a function, it will be private to that function. If you really need to you could set it on window explicitly.
In source1.js
function foo() {
window.source1Var = 3;
}
In source2.js
function bar() {
console.log(source1Var); // this will search window if it cannot find in the local scope.
}
What is the problem you're trying to solve? It is generally better to use some form of dependency injection, event listeners, builder pattern etc. rather than using global variables.
do something like in your first .js
var VAR = {
myvalue: "hai"
};
then call it in second like
alert(VAR.myvalue);
It's easier than you think. If variable is global, you should access it from anywhere.
// source1.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
And in another file:
// source2.js
alert (colorCodes.back); // alerts `#fff`