daveycroqet
daveycroqet

Reputation: 2727

Reset value(s) of 'this' from outside their scope/function

Description of Problem (Fiddle):

I am attempting to empty/unset the values of this.rotated and this.locked from an event outside the one where they are originally defined. I need these 'lockout' variables to be unique for each kitten in order to prevent subsequent .mousedown() events on them.

The end goal is to be able to continually click the three smaller cats, have the fourth large cat fade in, click the fourth cat, and then have everything reset.

My grasp of this is loose at best; well enough to use it in most cases, but sorely lacking in a thorough understanding of its scope and usefulness. To be honest, I'm not even sure my title is accurate, but I couldn't think of another way to phrase it.

Code:

var count = 0;
$('.cats').each(function(i){
  $(this).mousedown(function() {
    $(this).css({
      'transform': 'rotate(45deg)',
      '-webkit-transform': 'rotate(45deg)'
    });
    this.rotated = 1, this.locked;
    if (this.rotated && !this.locked) {
      this.locked = 1;
      count++;
      if (count > 2) {
        $('#newCat').fadeIn();
      }
    }
  });
});

$('#newCat').mousedown(function() {
    $(this).fadeOut();
    $('.cats').fadeOut(function() {
        $(this).css({
            'transform': 'rotate(0deg)',
            '-webkit-transform': 'rotate(0deg)'
        })
        .fadeIn();
    });
});

Upvotes: 2

Views: 61

Answers (1)

Shadaez
Shadaez

Reputation: 412

You seem to have almost had it. when you do $('.cats').fadeOut() you're back in the scope of the cats and this.locked and this.rotated can be accessed again, though you also need to decrement count again as they get locked.

Working fiddle: http://jsfiddle.net/SB57D/4/

Also, locked and rotated are serving the same purpose, you could get rid of one of them.

Upvotes: 2

Related Questions