if anyone can help me I am having a problem with closures and retrieving a private variable declared that is a element selected by id using jquery. I have a module like so:
var package = package || {};
(function() {
if(!package.slider)
package.slider = {};
function Slider() {
}
// --------- /Public Members --------- //
Slider.prototype = {
init: function(){
_setEvents();
}
};
// --------- Public Members --------- //
// --------- Private Members --------- //
var shoePreview = $('#shoe-preview'); /*somehow this variable does NOT get recognised even though I have it in the DOM.*/
function _setEvents(){
$.subscribe('getAllPerspectives', function(event){ _getAllPerspectives() });
$.subscribe('showPreview', _show);
$.subscribe('hidePreview', _hide);
}
function _getAllPerspectives(){
_getAngleShoeImage(helper.getCurrentAngle());
$.each(constants.angles, function(key, val){
if(val != helper.getCurrentAngle()){
_getAngleShoeImage(val);
}
});
}
function _getAngleShoeImage(angle){
var shoeImage = shoePreview;
shoeImage.html('<p>Hello World</p>');
}
var that = new Slider();
package.slider = that;
})();
$(document).ready(function(){
$.each(package, function (key, val){
val.init();
});
});
Now If you looked in the code, there is a variable called shoePreview, which I assume would not be accessible to anything outside the module.
Now somewhere in the code later I will call some methods which will trigger _getAngleShoeImage where I have variable inside called shoeImage set to the private shoePreview variable.
The problem is that once I try to use jquery’s html() call it seems to not recognise what the shoePreview variable is.
I’ve tested this with substituting var shoeImage = $(‘#shoe-preview’), then calling html() with the desired markup and it works fine.
This problem is so small but it’s driving me nuts. Am I writing the var shoePreview = $(‘#shoe-preview’); in the wrong way or there’s something more to it. Any help will be appreciated.
Thanks.
Here is only one problem:
(function(){hackhackhack()})()literally mean – run the closure, it means you tried to access DOM before it ready, you just need to setup the var after init, not in main function,