0

I used to have a lot of things inside my click function. Now, I tried to refactor my code, by creating a function and call it back,that way I can re-use it in more than one places without repeating myself.

I'm a lil stuck now, and not sure what I did wrong here. I got 0 error and 0 warning on my .js file. I use JS lint.

Here is what I have at the moment.

function cbInit() {

    ($pbSection, $chSection, $chBtns, $chBtnsRow, $btnTime, $btnRemediation).hide();
    ($cbSection, $cbBtns).show();
    $btnBiDefault.removeClass('btn-bi-default-clicked');
    $btnAssignmentPerformance.addClass('btn-bi-default-clicked');
    $cbImage.attr('src', '/BIM/resources/images/monitorprogress/reports/02-Course Benchmark/Assignment.png');
}

$courseBenchmark.click(function(e) {
    e.preventDefault();

    cbInit();
}

Nothing got hide, no image loaded. It seems like cbInit(); never get execute at all.

  • How to trace down this kind of problem ?
  • Can someone help give me a little help here ?
cyb3rZ
  • 43,853
  • 82
  • 251
  • 430
  • Where are all of your variables (`$courseBenchmark`, `$pbSection`, etc.) defined? – Ken Herbert Apr 30 '15 at 00:08
  • Do you have a `$(document).ready(function {...});` anywhere in your code? – Ken Herbert Apr 30 '15 at 00:16
  • 3
    The expression `($pbSection, $chSection, $chBtns, $chBtnsRow, $btnTime, $btnRemediation)` is equivalent to just `$btnRemediation`. Learn about the [comma operator](http://stackoverflow.com/questions/3561043/what-does-a-comma-do) – Barmar Apr 30 '15 at 00:18
  • @Barmar : Ohh really ! Thanks for this tip. Do you know how to tweak that ? – cyb3rZ Apr 30 '15 at 00:19

2 Answers2

1

Putting a list of variables in parentheses does not automatically map the method call over all of them, it just invokes the comma operator, which evaluates to the last one in the list. You can use the jQuery method .add() to merge collections.

function cbInit() {

    $pbSection.add($chSection).add($chBtns).add($chBtnsRow).add($btnTime).add( $btnRemediation).hide();
    $cbSection.add($cbBtns).show();
    $btnBiDefault.removeClass('btn-bi-default-clicked');
    $btnAssignmentPerformance.addClass('btn-bi-default-clicked');
    $cbImage.attr('src', '/BIM/resources/images/monitorprogress/reports/02-Course Benchmark/Assignment.png');
}
Barmar
  • 596,455
  • 48
  • 393
  • 495
1

This is not how javascript (thus jquery) works:

($pbSection, $chSection, $chBtns, $chBtnsRow, $btnTime, $btnRemediation).hide();

If you need a one liner you can do this:

[$pbSection, $chSection, $chBtns, $chBtnsRow, $btnTime, $btnRemediation].forEach(function($item){$item.hide()});
Sinan
  • 10,875
  • 6
  • 34
  • 48