3

Im using the following code which works and my question how should I write it better,since when I use EsLint I got red message that saying that dont make function without loop,currently Im new to JS so I dont know how to do that better...

    for (var i = 0; i < allChildren.length; i++) {
        allChildren[i].attachChange(function(){
                this.getChecked() ? nSelectedChildren+=1 : nSelectedChildren-=1;
                if(nSelectedChildren === 0){
                    oParent.toggle("Unchecked");
                }
                else if(nSelectedChildren === allChildren.length){
                    oParent.toggle("Checked");
                }
                else{
                    oParent.toggle("Mixed");
                }
            }
        );
John Jerrby
  • 1,683
  • 7
  • 31
  • 68

1 Answers1

1

What EsLint meant what it should be, i think, is:

function foo(){
    this.getChecked() ? nSelectedChildren+=1 : nSelectedChildren-=1;
    if(nSelectedChildren === 0){
        oParent.toggle("Unchecked");
    }
    else if(nSelectedChildren === allChildren.length){
        oParent.toggle("Checked");
    }
    else{
        oParent.toggle("Mixed");
    }
}

for (var i = 0; i < allChildren.length; i++) {
    allChildren[i].attachChange(foo);
}

Don't define functions within loops

Funonly
  • 818
  • 1
  • 8
  • 22