3
\$\begingroup\$

I've a lot of code blocks that hide/show some block.

$('#Back').on('click', function () {
    $('#FormRow').hide();
    $('#TableRow').show();
});

$('#AddLanguageShow').on('click', function () {
    $('#FormRow').show();
    $("#TableRow").hide();
});


$('table').on('click', 'button.edit', function (evt) {
    $('#FormRow').show();
    $('#TableRow').hide();
    languageManager.load(getRowId($(this)));
});

Is it possible to split logic of changing blocks visibility ?

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Can you provide us more code, it is not clear why you would show or hide stuff right now. \$\endgroup\$
    – konijn
    May 15, 2014 at 18:21
  • \$\begingroup\$ Not sure if applicable to your case, but did you consider the toggle() function? api.jquery.com/toggle \$\endgroup\$
    – Pevara
    May 15, 2014 at 19:09

2 Answers 2

3
\$\begingroup\$

Extract the duplicated code to a function:

function showOneHideOther(elToShow, elToHide) {
    $(elToShow).show();
    $(elToHide).hide();
}

You can reuse the function anyplace now:

$('#Back').on('click', function() {
    showOneHideOther('#TableRow', '#FormRow')
});
$('#AddLanguageShow').on('click', function() {
    showOneHideOther('#FormRow', '#TableRow')
});

$('table').on('click', 'button.edit', function (evt) {
    showOneHideOther('#FormRow', '#TableRow')
    languageManager.load(getRowId($(this)));
});
\$\endgroup\$
2
  • \$\begingroup\$ I believe this won't work. You're setting undefined to the handlers for #Back and #AddLanguageShow. \$\endgroup\$
    – Joseph
    May 15, 2014 at 19:02
  • 1
    \$\begingroup\$ You are right @JosephtheDreamer, I already fixed it. Thanks for pointing out my error! \$\endgroup\$ May 15, 2014 at 19:15
1
\$\begingroup\$

It looks like you have one set of interactions that show the form, and another that show the table. How about something like this?

var uiThatHidesTable = [$('#button1'), $('#button3')];
var uiThatHidesForm  = [$('#button2')];

var hideTable = function() { $('#TableRow').hide(); $('#FormRow').show(); }
var hideForm = function() { $('#FormRow').hide(); $('#TableRow').show(); }

uiThatHidesTable.forEach(function(el) { el.on('click', hideTable); });   
uiThatHidesForm.forEach(function(el) { el.on('click', hideForm); });

// you can still bind additional things to do out here    
$('#button2').on('click', function() { alert("pushed 2"); });

Fiddle here: http://jsfiddle.net/T7swj/

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.