0

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?

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I would at least put them inside the ready event handler, so that they are not global. But in any case, this would allow to only have one slide box object.
1

If you are gonna use them a lot, I would made them a property of the object.

1 Comment

Global is global. How is this related to closures? Anyways, I think making them properties of the object is the best solution.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.