I’ve search for this but couldn’t find a suitable answer.
Basically I’m making a new plugin, and I’m using the format from this site:
However, I am having trouble with variable scope (or maybe I’m doing it the wrong way).
If I have this (truncated so it’s easier to read):
(function($)
{
$.rp_popup = { 'version' : "0.0.1" };
$.fn.rp_popup = function(options)
{
var $element = $(this);
var options = $.extend({}, $.rp_popup.defaults, options);
$element.click(function()
{
return false;
});
};
$.rp_popup.open_popup = function()
{
// I want to access options here
debug(options);
}
$.rp_popup.defaults = {
modal : false
}
})(jQuery);
Ignore the fact the plugin does nothing
How can I access options from the open_popup function? I know I can put it inside the rp_popup function but that seems a little hacky (although this is the way pretty photo does it).
And jquery UI does it in a way where you pass a function as a string, and then uses eval to call it, so:
$.rp_popup("open")
but I’m not sure about that.
So yea, sorry for the long post, but what’s the best way to do it?
Please show your code that is having the issue and we’ll get you back on track.
It helps to know that using var to declare a variable inside a function does clobber the variable of the same name from a higher scope.
In other words, to access a variable from a higher scope (such as outside of a function) do not use the var keyword inside the function for that variable.
What you could do as an alternative, is to move the var statement for that variable up out of the function, so that it is then accessible from both functions.
I would kindly suggest you don’t advise someone on something that you yourself are unsure about, like in this case. Not only was your advice ambiguous, it also makes no sense in the context of answering the original question.
@Blue - It’s the other way around isn’t it? “var” makes them local? I guess I’ll have to pass them in then as parameters, which does make sense. Cheers.
@wisher - Cheers for the link, looks good. In my case, wrapping it in an each loop wouldn’t be necessary I don’t think.