Timsalabim
Timsalabim

Reputation: 3

Trouble with click not unbinding

I'm building a small adventure to help me understand some concepts of JQuery/Javascript and I've hit a snag.

What I'm trying to do is by clicking on a "take" button and then on an item on the screen to move it to the inventory. Good news is, that all works. Bad news is that if I press another item without using the "take" button first it goes straight to my inventory.

Same problem with "look". You should have to press "look" first and then the item to get a description, but once it's pressed it'll give every item you click a description straight away.

You can imagine that once you've pressed them both every item you click without clicking another button will give you a description and end up in your inventory straight away.

This is how I'm trying to get it to unbind:

$("#take").click(function () {
    $("#zilverenKogel").click(function () {
        $("#zilverenKogel").fadeOut(1200, 0);
        $("#invKogel").fadeTo(1500, 1);
        $("#take").unbind("click");

Any help will be greatly appreciated!

Mofx solved it for me. End, and working result, is:

 var state = null;
$( "#take" ).click(function () {state = "take";})
$( "#look" ).click(function () {state = "look";})


$( "#zilverenKogel" ).click(function () {
    if (state == "take") {
        $("#zilverenKogel").fadeOut(1200, 0);
        $("#invKogel").fadeTo(1500, 1);
      state=null;
    } else if (state == "look") {
        alert("blablabla");
       state=null;
    }

});

thanks a lot Mofx!

Upvotes: 0

Views: 74

Answers (1)

MofX
MofX

Reputation: 1568

You unbind the wrong event. You want to unbind the event on "#zilverenKogel", because that is the one doing the "take-action".

I also suspect, you connect events to other elements as well within "$("#take").click(function () {". You would have to disconnect them all. After the action was taken or another action was selected.

Maybe a statemachine would be a better solution here. Something like:

var state = null;
$("#take").click(function () {state = "take";}
$("#look").click(function () {state = "look";}

$("#zilverenKogel").click(function () {
  if (state == "take") {
    moveToInventory();
  } else if (state == "look") {
    showDescription();
  }
}

Upvotes: 3

Related Questions