Tim T
Tim T

Reputation: 333

jQuery how to call a method within a prototype?

jQuery:

    function Morphing( button, container, content) {
    this.button = button;
    this.container = container;
    this.content = content;
    this.overlay = $('div.overlay');
}

Morphing.prototype.startMorph = function() {
    this.button.on('click', function() {
        $(this).fadeOut(200);
        Morphing.containerMove();
        // Work on from here!
        // setTimeout(Morphing.containerMove, 200);
    });
};

Morphing.prototype.containerMove = function() {
    console.log(this);
    this.overlay.fadeIn();
    this.container.addClass('active');

    this.container.animate(Morphing.endPosition, 400, function() {
            this.content.fadeIn();
            this.span.fadeIn();
            Morphing.close();
    });
};

Im trying to run the containerMove function when the button is clicked, but instead, I receive the error:

[Error] TypeError: undefined is not a function (evaluating 'Morphing.containerMove()')
    (anonymous function) (newScript.js, line 11)
    dispatch (jquery.min.js, line 3)
    i (jquery.min.js, line 3)

This is the only error. I presume that it's because I'm calling the method incorrectly? Thanks.

On a side note: Is writing methods within prototypes like I have done a good practise?

Extra code:

Forgot to mention, this is in my index.html :

<script>
$(document).ready(function() {

    var morph = new Morphing( $('button.morphButton'), $('div.morphContainer'), $('h1.content, p.content') );

    morph.startMorph();

});

</script>

Upvotes: 2

Views: 365

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92324

Easiest way is to store the original this in a closure

Morphing.prototype.startMorph = function() {
    var me = this;
    this.button.on('click', function() {
        $(this).fadeOut(200);
        me.containerMove();
        // Now for the set timeout, you'll want to make sure it's
        // called with the corect `this`, You can use Function.bind
        // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
        setTimeout(me.containerMove.bind(me), 200);
    });
};

In your event handler, this points to the element itself, as you seem to understand from the fact that you call $(this).fadeOut(200); but you need access what this was outside of the handler.

Upvotes: 3

Related Questions