jQuery multibinding events(edit)

Sometimes I find myself using the same event handler for more than one event on an element. Typically I just put the function in the global name space (or perhaps privately within the scope of the ready function depending on how the mood takes me), and then I'll refer to the function twice. But this feels a bit like duplication.

To hide my duplication, I've written wasted my time creating a simple plugin that gives me the ability to bind to more than one event at once.

Paul kindly pointed out that the functionality is native to jQuery - so here's the examples.

That'll teach me for writing code late at night! I completely overlooked that this is native functionality within jQuery: $('input').bind('keyup change', fn);

I'm leaving the post here, but have retracted the download link (and tweaked the post a bit).

Typical code

This is where I would normally need the function twice. Here's the lame version of the code:

$('input').keyup(function () {
  var i = 255-this.value, j = this.value;
  $('body').css('background', 'rgb(' + [i,i,j].join(',') + ')');
}).change(function () {
  var i = 255-this.value, j = this.value;
  $('body').css('background', 'rgb(' + [i,i,j].join(',') + ')');
});

Which can be simplified to:

function colour() {
  var i = 255-this.value, j = this.value;
  $('body').css('background', 'rgb(' + [i,i,j].join(',') + ')');
}

$('input').keyup(colour).change(colour);

But the colour function feels redundant because it's only required for that little bit of closure (and sure, I know for high performance apps, it's probably better that way, but we're just hacking right now).

Multibind handler

With multibinding, you can bind the same event handler to more than one event:

$('input').bind('keyup change', function () {
  var i = 255-this.value, j = this.value;
  $('body').css('background', 'rgb(' + [i,i,j].join(',') + ')');
});

Comments

comments powered by Disqus