Question

I just started using YUI, and I think I am confused about how to break out of the loops in the NodeList .some() method.

http://yuilibrary.com/yui/docs/api/classes/NodeList.html#method_some

It says in the API docs, that the function needs to return true.

I have a select tag with a two options:

 <select id="carrier">
  <option value="1">Text 1</option>
  <option value="2">Another Text 2</option>
 </select>

I'm trying to loop through the options until the option text matches the text, I'm looking for. I thought this was the way to make the callback function return true. However, when I ran this, I kept seeing the console.log() in the else branch. So, I think I am not returning true in the proper place, but I am not sure what I am supposed to do.

 YUI().use('node', function(Y) {
     var targetText = 'Another Text 2';

     Y.one('#carrier').get('options').some(function(currentNode, index, NodeList) {

        if (currentNode.get('text') === targetText) {
          return true;
        } else {
          console.log('Should NOT see this.');
        }
     });
});
Était-ce utile?

La solution

some() is behaving correctly. The first element your anonymous function sees is 'Text 1', which does not match targetText, so the function outputs to the console and the loop continues. In the next iteration, your condition matches and 'return true' breaks from the loop.

If you edit your HTML and reverse the order of the option elements, you will see the behavior you are expecting.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top