Reputation: 551
I have the following structure
// script1.js
jQuery(document).ready(function($) {
var somevar;
$('somelem').myPlugin();
});
// script2.js
(function($) {
$.fn.myPlugin = function(options) {
// access and modify 'somevar' here so that it gets modified
// in the function which called a plugin
};
});
Upvotes: 3
Views: 9353
Reputation: 82
You can write function that will set value from variable and then call she in another script.
//script1.js
var somevar;
function setSomevar(value){
somevar = value;
}
function getSomevar(){
return somevar;
}
jQuery(document).ready(function($) {
$('somelem').myPlugin();
});
Now you can call function setSomevar and pass the value to variable. I hope that helps. Best Regards.
Upvotes: -1
Reputation: 7738
When you pass a primitive type, it is passed by value. But, if you pass an object then it'll pass by reference. So, you can do that -
jQuery(document).ready(function($) {
var somevar = {val: 5};
$(document).myPlugin(somevar);
alert(somevar.val);
});
// script2.js
(function($) {
$.fn.myPlugin = function(options) {
options.val ++;
// access and modify 'somevar' here so that it gets modified
// in the function which called a plugin
};
})(jQuery);
see the live demo :: http://jsfiddle.net/rifat/EdRFm/
Upvotes: 3
Reputation: 337
You could let the plugin function return a value and assign that to somevar
somevar = $('someelem').myPlugin();
Or you could pass an callback as parameter to your plugin method
// Script 1
var somevar;
$('someelem').myPlugin(function(newValue) {
somevar = newValue;
});
// Script 2
$.fn.myPlugin = function(callback) {
...
callback(newValueForSomeVar);
}
Upvotes: 0
Reputation: 6653
you could create a singleton class for your global variables.
Upvotes: 0