Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lint error within loop on function [duplicate]

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");
                }
            }
        );
like image 752
John Jerrby Avatar asked Mar 12 '26 21:03

John Jerrby


1 Answers

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

like image 107
Funonly Avatar answered Mar 15 '26 11:03

Funonly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!