views:

39

answers:

2

Say when a checkbox is checked/unchecked, I want specific behavior to occur.

Now if there are multiple points in my code where I set a checkbox as checked/unchecked, I have to run through the same logic ever time.

What is a way I can encapsulate the logic that occurs when a checkbox is checked, and just re-use that logic?

+4  A: 

My guess is that you're currently binding click event handlers like this:

$('some-selector').click(function (event)
{
    // do fancy stuff here
});

To encapsulate that logic, you just need to switch from using an anonymous function, to a function that you can reuse, like this:

function handleClicks(event)
{
    // do fancy stuff here
}

$('some-selector').click(handleClicks);
$('some-other-selector').click(handleClicks);

How's that?


I might also take a guess at the fact that the logic you're writing and rewriting is to wire a "check-all" sort of checkbox to a group of checkboxes. I wrote a jQuery plugin recently to handle exactly this sort of thing.

I never got around to uploading it properly to GitHub - here's the gist of it. Let me know if you'd like to actually use it, and I can explain its usage - it's pretty darn simple.

Matt Ball
good guessing!...
Blankman
@Blankman: need an explanation of the plugin?
Matt Ball
+2  A: 

Just extending what 'Bears will eat you' said about using non-anonymous functions, you should all so integrate your own function library to jquery:

Create your functions like so

$.fn.handleClicks = function (){
    $(this).click(function(event){
        alert('Click');
        return false
    })
}

Then you can use them like so, makes things a little more neater and a little lesser code. IMO;

$('a').handleClicks();    ​
RobertPitt