Reputation: 33655
In jQuery is it possible to create a function that sets a variable which I can then access in another function. i.e. I need a global variable that can be accessed anywhere on the page.
Examples
$.fn.getRedemptionID = function(){
var myVar = data.DATA[0].item1;
}
Upvotes: 0
Views: 212
Reputation: 4236
A better way would be to use closure, to save your variable value in the following manner:
var application = (function(){
var my_var;
return {
get_var: function(){
return my_var;
},
set_var: function(value){
my_var = value;
}
}
})();
application.set_var(34);
application.get_var;
It's better than using Global variables.
Upvotes: 0
Reputation: 7618
jQuery is still JavaScript, and can still be used like JavaScript. I.e. if you declare something outside of any block, it is global and can be accessed anywhere.
E.g.
var global = 42;
$(document).ready(function() {
global = $('#something').val();
});
Upvotes: 0
Reputation: 46657
1) Global variables are bad.
2) Yes:
// explicit global (preferred)
$.fn.getRedemptionID = function(){
window.myVar = data.DATA[0].item1;
}
// implicit global
$.fn.getRedemptionID = function(){
myVar = data.DATA[0].item1;
}
Upvotes: 3
Reputation: 241
Just do this :
var myGlobalVar = null;
$.fn.getRedemptionID = function(){
myGlobalVar = data.DATA[0].item1;
}
Then you can access myGlobalVar everywhere :)
Upvotes: 0