\$\begingroup\$
\$\endgroup\$
2
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 ?
200_success
145k22 gold badges190 silver badges478 bronze badges
2 Answers 2
\$\begingroup\$
\$\endgroup\$
2
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)));
});
answered May 15, 2014 at 18:57
-
\$\begingroup\$ I believe this won't work. You're setting
undefined
to the handlers for#Back
and#AddLanguageShow
. \$\endgroup\$Joseph– Joseph2014年05月15日 19:02:04 +00:00Commented May 15, 2014 at 19:02 -
1\$\begingroup\$ You are right @JosephtheDreamer, I already fixed it. Thanks for pointing out my error! \$\endgroup\$Juliano Alves– Juliano Alves2014年05月15日 19:15:44 +00:00Commented May 15, 2014 at 19:15
\$\begingroup\$
\$\endgroup\$
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/
default
toggle()
function? api.jquery.com/toggle \$\endgroup\$