0

i have the following object

function AnimatedObject(object)
{
    this.object = object;
    /*
        Functions
     */
    this.fadeOutAnimation = fadeOutAnimation;
    this.objectToggle = objectToggle;
    this.objectClick = objectClick;
}
function fadeOutAnimation()
{
    this.object.animate({
        opacity: 0.25,
        left: "+=150",
        height: "toggle"
    }, 2500, function() {
        this.objectToggle();
    });

}

function objectToggle()
{
    this.object.toggle();
}

From inside my animate function i am called this.objectToggle();

However when it completes the animation i get undefined is not a function

I am quite certian that it is because of the inner callback function that does not have a reference to the object

My question is how can i give it a reference to my object and thereby allow me to call its functions from inside the callback function?

2 Answers 2

1

Bind the function to the right context:

function fadeOutAnimation()
{
    this.object.animate({
        opacity: 0.25,
        left: "+=150",
        height: "toggle"
    }, 2500, function() {
        this.objectToggle();
    }.bind(this));

}

Or just store a reference to this:

function fadeOutAnimation()
{
    var that = this;
    this.object.animate({
        opacity: 0.25,
        left: "+=150",
        height: "toggle"
    }, 2500, function() {
        that.objectToggle();
    });

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

Comments

1

Inside animate function this refers to the animating div and context of the this has changed. you can bind this or can save reference earlier in the code

function fadeOutAnimation()
{
    that = this;
    this.object.animate({
        opacity: 0.25,
        left: "+=150",
        height: "toggle"
    }, 2500, function() {
        that.objectToggle();
    });

}

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.