In my init
I have set some variables and one animate that uses those variables.
What if I want to use that same animate/variables in my clickSlide
?
http://jsfiddle.net/lollero/4WfZa/ ( This obviously wouldn't work. )
I could make it global http://jsfiddle.net/lollero/4WfZa/1/ ( by removing the var
)
Question is: Is there a better way, or is this perfectly ok way of doing it?
Put the variable outside the function and than get the value
var getWidth ;
var getHeight ;
$(function(){
var slideBox = {
gb: $('#box'),
init: function() {
sb = this,
getBox = sb.gb,
getWidth = getBox.width(),
getHeight = getBox.height();
getBox.animate({ marginLeft: '+='+getWidth }, 600 );
$("#button").on("click", this.clickSlide);
},
clickSlide: function() {
getBox.animate({ marginLeft: '+='+getWidth }, 600 );
}
};
slideBox.init();
});
than make use in the function so that you can get the vlue in you clickside function
If you are gonna use them a lot, I would made them a property of the object.
Your variables seem unnecessary, you can access everything you need to like this: http://jsfiddle.net/4WfZa/6/. If you do need to store them you can always add them to the slideBox object and then populate them in init. This way the variables are stored against the object and can be used in any of the functions within it.
For a great article on javascript namespacing, including how to set up private and public variables see this article.
ready
event handler, so that they are not global. But in any case, this would allow to only have one slide box object - Felix Kling 2012-04-04 08:28