views:

253

answers:

2

The jQuery documentation for the .toggle() method states:

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting.

The assumptions built into .toggle have proven limiting for my current task, but the documentation doesn't elaborate on how to implement the same behavior. I need to pass eventData to the handler functions provided to toggle(), but it appears that only .bind() will support this, not .toggle().

My first inclination is to use a flag that's global to a single handler function to store the click state. In other words, rather than:

$('a').toggle(function() {
  alert('odd number of clicks');
}, function() {
  alert('even number of clicks');
});

do this:

var clicks = true;
$('a').click(function() {
  if (clicks) {
    alert('odd number of clicks');
    clicks = false;
  } else {
    alert('even number of clicks');
    clicks = true;
  }
});

I haven't tested the latter, but I suspect it would work. Is this the best way to do something like this, or is there a better way that I'm missing?

Thanks!

+4  A: 

Seems like a reasonable way to do it... I'd just suggest that you make use of jQuery's data storage utilities rather than introducing an extra variable (which could become a headache if you wanted to keep track of a whole bunch of links). So based of your example:

$('a').click(function() {
  var clicks = $(this).data('clicks');
  if (clicks) {
    alert('odd number of clicks');
  } else {
    alert('even number of clicks');
  }
  $(this).data("clicks", !clicks);
});
Alconja
Thanks, Alconja - good answer! I appreciate the concise code example.
Bungle
+2  A: 

Why not just use toggle and make your own function to call your functions with extra event data?

function myEvent(e) {
  alert(e.data.msg);
  return false;
}
function evtDataHandler(fun, data) {
  return function(e) {
    if (!e.data) e.data = {};
    $.extend(e.data, data);
    return fun.apply(this, arguments);
  }
}
$('a').toggle(
  evtDataHandler(myEvent, {msg:'Odd number of clicks'}),
  evtDataHandler(myEvent, {msg:'Even number of clicks'})
);
gnarf