Domanda

I'm actually doing a very simple example about HTML5 forms and custom UI interface validation updates. I'm pretty close to the result in term of behavior however i'm stuck with a little detail in my JS code.

Basically i'm attaching an input event to all form's input elements. The callback function just check current element validity and apply custom class to style the element in kinda 'realtime'.

The only problem i'm facing is that i need to pass the current element to the parameter of the callback function in the event handler. As i need to attach this event to each input element i'm using a for loop.

I get the jslint warning : Don't make functions within a loop.

I'm not sure how to solve this (i do understand what it means). I don't know to pass the element as a parameter to the callback function without using an anonymous function.

So the questions is : how to pass the current element as a parameter to an external function to solve the jslint warning.

If someone got a better way to handle that and could correct it to a more efficient code that would be much appreciated. That's example could serve later on for some students.

here's a codepen : http://codepen.io/anon/pen/bGDsB

È stato utile?

Soluzione

Your case can be solved by replacing the for loop and adding a function:

for (var i=0; i<inputs.length; i++) {
    attachCheck(inputs[i]);
}
function attachCheck(inp) {
    inp.addEventListener('input', function() {
        check(this);
    });
}

Wouldn't it be better though to modify check() to use this, like:

function check() {
    if(this.value.length) {
        // ... all elm replaced by this ...
}

And the loop:

for (var i=0; i<inputs.length; i++) {
    inputs[i].addEventListener('input', check);
}

Altri suggerimenti

Rather than define a new function that simply calls check(), you can pass check directly to addEventListener():

  for (var i=0; i<inputs.length; i++) {
      inputs[i].addEventListener('input', check);
  }

You can then alter check() slightly to account for this:

  function check(e) {
      var elm = e.srcElement;
      ...
  }

I've not tested this against jsLint, but it does avoid creating a new function in each iteration of the loop.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top