return value from js file - javascript

I have two js file in my html page . If the first one begins with :
(function($){
..
..
}(jQuery));
can I insert a var into function($,varname) , return it's value and use it in the other file?

You need a global variable for this. You can do this in one of a few ways. Let's assume we need to send the value "Bacon" to the other script.
(function($){
window.myScriptsExports = "Bacon";
}(jQuery));
// OR
var myScriptsExports = (function($){
// other code
return "Bacon";
// NO other code
}(jQuery));
// OR (not really recommended)
(function($){
// other code
$.myScriptsExports = "Bacon";
// other code
}(jQuery));

You can improve the code by using global namespace which goes like:
(function($,global){
var _obj = {};
_obj.property1 = 'Property1';
_obj.function1 = function() { console.log('Function 1');};
global.myObject = _obj;
}(jQuery,window));
//accessing
window.myObject.property1
//or
window.myObject.function1()

Supposing your function is synchrone, you may set a global function :
(function($){
..
var myvar = 666;
window.getMyVar = function() {
return myvar;
};
..
}(jQuery));
and you can use it from the other function if the second file is imported after this one :
(function($){
..
var myprevisouslysetvar = window.getMyVar();
..
}(jQuery));
Note that the files doesn't matter in javascript : your page would work the same (apart details if you have "use strict") with both files concatenated.

Related

Pass a value and print it in javascript

I'm trying to pass a lang variable in my js files.
Actually I have this:
<script src="assets/js/plugins.js?lang=en"></script>
In plugins.js, I have this:
var LIBS = {
// Chart libraries
validation: [
"assets/libs/validation/jquery.validation.min.js",
"assets/libs/validation/lang/xxxxxx.min.js"
],
...
};
How can I get the lang value passed to replace my xxxxxx by the lang en ?
Thanks.
try this in your plugin.js
var LIBS = {
// Chart libraries
validation: [
"assets/libs/validation/jquery.validation.min.js",
"assets/libs/validation/lang/xxxxxx.min.js"
]
};
LIBS.tmpValidation = LIBS.validation;
LIBS.validation = [];
LIBS.lang = "en";
Object.defineProperty(LIBS, "validation", {
get : function(){
var self = this;
return this.tmpValidation.map(function(item){
return item.replace(/xxxxxx/g, self.lang)
})
}
});
console.log(LIBS.validation);
You can now define your plugin in such a way that lang property is set to LIBS before invoking LIBS.validation
You can use a global variable.
Global variable:
I've used an object here to store settings, you could add more settings, if you wish
var settings = { lang:'en' };
Your other script (plugins.js):
var LIBS = {
// Chart libraries
validation: [
'assets/libs/validation/jquery.validation.min.js',
'assets/libs/validation/lang/' + settings.lang + '.min.js'
],
...
};
Here's a full example script that does precisely what I'm talking about above. I've got LIBS declared in the same script, but it could just as easily be included in plugins.js and declared below the setting of the global settings variable in this script instead...
Example Script:
<script>
var settings = { lang:'en' };
console.log(settings); // Show that the value has been set.
var LIBS = {
// Chart libraries
validation: [
'assets/libs/validation/jquery.validation.min.js',
'assets/libs/validation/lang/' + settings.lang + '.min.js'
]
};
// Show that LIBS has been set with the language setting from the global variable.
console.log(LIBS);
</script>
After you've run this, then you will see that the variable has been picked up and the second entry in the array is assets/libs/validation/lang/en.min.js
Or to be closer to your own example...
<script>
var settings = { lang:'en' };
console.log(settings); // Show that the value has been set.
</script>
<!-- Following line must come after the script above
this JS file can now access that global settings variable -->
<script src="plugins.js"></script>
try
var s = document.getElementsByTagName('script'),
ss = s[s.length-1];
lang = ss.src.match(/\?lang=(\w\w)/);
// sure... check it exists!
console.debug(lang[1]);
inside plugins.js

How to use javascript namespaces?

I am trying to figure out JavaScript namespaces... I would like to write couple of functions and secure them in namespaces like below.. but I think I don't get it very well..This is too simple question but it will be clear for me I guess If I see why that doesn't work..
Here an exp that I am trying:
var myApp = {
getTxt: function(x){
x.click(function(){
var txt = $(this).html();
alert(txt);
});
};
};
call myApp:
var box = $('.js-box');
alert(myApp.getTxt(box));
I think MyApp is created rightly but I am not sure about calling and firing the getTxt function..
Calling that:
myApp.getTxt(box)
doesn't mean to fire x.click function..? Why does it turn an object?
What am I doing wrong here? Thanx!
http://jsfiddle.net/67b02cht/1/
You are defining myApp as an object, So here is a problem, You are giving ; after defining the field, which you can't. It'll cause a syntax error.
var myApp = {
getTxt: function(x){
x.click(function(){
var txt = $(this).html();
alert(txt);
});
} //<<<<-------------here was a semicolon,
};
And you are calling the function like bellow in alert it will cause an undefined alert because you are not returning anything from the function. Just call
myApp.getTxt(box)
And it will show the content on click.
DEMO
How about a modular approach.
var MyApp = MyApp || {};
MyApp.Module = (function () {
function App() {
}
App.prototype.getTxt = function(x){
//your code here
}
return App;
})();
Use it this way:
var box = $('.js-box');
alert(new MyApp.Module.getTxt(box));

Javascript convert string to be called as function

I have the following scenario where I need to call a function based on the data attributes of the html element.
function func1(arg1){
alert("func1");
}
function func2(arg2){
alert("func2");
}
jQuery(document).on('click', '.func-class', function(){
var funcName = jQuery(this).data('func-name');
var funcArg = jQuery(this).data('func-arg');
//Need to call funcName(funcArg) here
});
HTML:
<div data-func-name="func1" data-func-arg="arg1" class="func-class">Func1</div>
<div data-func-name="func2" data-func-arg="arg2" class="func-class">Func2</div>
JSFiddle of the same:
http://jsfiddle.net/E4HeT/
If those functions are defined in ths global scope, you can do this:
window[funcName](funcArg);
Otherwise, I would suggest putting them in an object like so:
var functions = {
"func1":func1,
"func2":func2
};
functions[funcName](funcArg);
This second one is actually safer, as it helps prevent arbitrary code execution.
you can do like the following this
window[funcName](funcArg)
but you will have to get the reference of the function by setting it in a object for example (like what i did in the window object) because its private in the jQuery.ready function
$('.func-class').click(function(){
var toCallArg = $(this).data('func-arg');
var toCall = function(toCallArg){
//your code
};
toCall(toCallArg);
});

How to define Global Arrays?

Code example:
<script>
var data = new Array();
data[0] = 'hi';
data[1] = 'bye';
</script>
<script>
alert(data[0]);
</script>
This gives the following error: data is not defined
How do you make something like this work? Especially if the first <script> block is being loaded on the page by ajax, and the second block is working from it. jQuery solution is acceptable.
New is not a keyword.
Use:
var data = new Array();
Or, more succinctly:
var data = [];
After your edit you mention that the first script block is loaded asynchronously. Your code will not work as written. data is a global variable, once it is loaded onto the page. You need to use a callback pattern to properly execute the code.
Since you haven't posted the asynchronous code I am not going to provide a callback sample. Though, a quick solution follows:
var interval = setInterval(function(){
if(data) {
/* ... use data ... */
clearInterval(interval);
}
}, 500);
To create a global variable, just omit 'var' from the statement. When you omit 'var', you're actually creating the variable in the window namespace.
So, zz = 1 is actually window.zz = 1
If you really wanted to, you could explicitly say
window.data = new Array(); //remember that new should be lowercase.
But you can write that faster anyway by saying
data = ['hi','bye'];
alert(data);
If you're using jQuery, perhaps you should try .getScript() rather than using .html();
// in separate file
data[0] = 'hi';
data[1] = 'bye';
// in main file
var data = [];
$.getScript(url).done(function() {
alert(data[0]);
}).fail(function() {
// handle error
});
<script>
data = [];
data[0] = 'hi';
data[1] = 'bye';
</script>
<script>
alert(data[0]);
</script>
use this, remove var makes variable global

call a java script function in a js file from a function of another js file

my problem is that i have two js file (1.js, 2.js), in both has the same functionality , methods(or like a copy of file). now i want to call a function (like _finish() ) from one js(1.js) file to another js file(2.js) file. can anyone give a solution.
Create your own namespace and pull all "public" methods (to your application) in there.
1.js
window.yourspace = window.yourspace || {};
window.yourspace.app = (function() {
var foo = 1;
return {
publicfunction: function() {
alert('hello world');
}
};
}());
2.js
window.yourspace = window.yourspace || {};
if( yourspace )
yourspace.app.publicfunction();
I agree with jAndy. In your case you must use namespaces.
For example, if you have script one defining variable a and then the second script defining it's own variable a, when the 2 scripts are put together, the last script executed by the browser overwrites the a variable :
//script 1
var a = 'script 1 value';
// ...
//script2
var a = 'script 2 value';
// ...
alert(a);
When you execute the above example, you'll see that the second script has redefined your a variable. So, the best way to do this without having name conflicts is using namespaces:
//script 1
script1Namespace.a = 'script 1 value';
// ...
//script2
script2Namespace.a = 'script 2 value';
// ...
alert(script1Namespace.a);
alert(script2Namespace.a);

Categories