Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a named function with for each and this

Tags:

javascript

I have found that not using anonymous functions has made my code more readable and self-documenting by flattening the code into more understandable, standalone functions. So I'd like to break out the following construct from:

function Save() {
   myVal = 3.14 // some arbitrary value
   $('#myID').each(function(index,element) {
      if ($(this).val() === myVal) {}
   });
}

Into:

function Save() {
   myVal = 3.14 // some arbitrary value
   $('#myID').each(myFunction);
}

function myFunction(index,element) {
   if ($(this).val() === myVal) {}
}

The problem with using .bind here, is that you lose the value of $(this) inside the each method, so (I don't think) I can bind myVal to myFunction.

Maybe I could use element instead of this?

Edit 1: I should have used .myClass instead of #myID for an example selector.

Edit 2: I'm not using bind in the proposed solution because I don't think bind would work.

Edit 3: I appreciate everyone saying that the first example is more readable. I'm just exploring the language and trying out different thoughts.

like image 214
Phillip Senn Avatar asked Feb 16 '23 21:02

Phillip Senn


1 Answers

And what about :

function Save() {
    myVal = 3.14 // some arbitrary value
    $('#myID').each(myFunction(myVal));
}

function myFunction(myVal) {
    return function(index, element) {
        if ($(this).val() === myVal) {}
    }
}
like image 79
Samuel Caillerie Avatar answered Feb 19 '23 10:02

Samuel Caillerie