all jazz
all jazz

Reputation: 2017

getting rid of duplicated code in jQuery

What is the most elegant way to beautify the following code? I would like to get rid of duplicated code:

$('#popup_settings_enable_name').click(function() {
    $el = $('#popup_settings_name_field');
    if ($(this).prop('checked')) {
        $el.removeAttr("disabled");
    } else {
        $el.attr("disabled", "disabled");
    }
}).each(function() {
    $el = $('#popup_settings_name_field');
    if ($(this).prop('checked')) {
        $el.removeAttr("disabled");
    } else {
        $el.attr("disabled", "disabled");
    }
});

Upvotes: 1

Views: 51

Answers (3)

Brian Ball
Brian Ball

Reputation: 12596

Triggering the click event manually could have unintended side effects (what if there are other delegates that have also been assigned the click event?)

I would suggest refactoring the duplicated code into its own method, then simply pass that method into the jQuery .click() function, and then passing it into the jQuery .each() function.

Upvotes: 0

Bergi
Bergi

Reputation: 664356

You can simply trigger the event to execute the handler for initialisation:

$('#popup_settings_enable_name').click(function() {
    …
}).click();

Another method would be to just use a function declaration:

function update() {
    // a little simplification:
    $('#popup_settings_name_field').prop("disabled", !this.checked);
}
$('#popup_settings_enable_name').click(update).each(update);

Upvotes: 0

Jon
Jon

Reputation: 437336

You can simply trigger the click event handler after installing it using .triggerHandler:

$('#popup_settings_enable_name')
.click(function() {
    // ...
})
.triggerHandler('click');

Note that .trigger would also do the exact same thing in many cases, but there are subtle differences between .trigger and .triggerHandler you should be aware of. The manual page makes clear mention of them.

Upvotes: 3

Related Questions