2014-09-05 4 views
2

Je suis en train de faire juste un peu validateur pour les entrées de forme (principalement pour la pratique et d'essayer des choses différentes)Comment se fait-il que je ne puisse pas appeler Array.prototype.map sur un tableau vide?

J'ai le code:

var Validator = function() { 
    this.elements = {}; 
    this.alerts = []; 
} 

Validator.prototype = { 
hookElement: function() { 
var that = this; 
$('#'+elementid).on('keyup', function(e) { 
    if (that.elements[name].val().length > that.elements[name].options.maxLength) { 
     that.alerts.map(function(x) { 
      if (x.name === name && x.option === 'maxLength') { 
       return true; 
      } else { 
       that.alerts.push({ 
       'alert': name + ' Cannot Be Greater Than ' + that.elements[name].options.maxLength, 
       'name': name, 
       'option': 'maxLength', 
       'visible': true 
      }); 
      } 
     }); 
    } else { 
     // Yet to add remover function 
    } 
}); 
} 

Lorsque j'appuie sur les touches dans le champ de saisie, le tableau never maps (déterminé avec console.log debugging) Pourquoi ne le passe-t-il pas, je sais qu'il est supposé effectuer une fonction sur chaque élément du tableau mais s'il n'y a pas d'éléments, est-ce qu'il ne fait vraiment rien? Comment puis-je faire ce travail.

L'idée est de ne pas ajouter au tableau si l'objet existe déjà dans le tableau.

modifier: Code complet ici, mais coller je ne pense pas que ce sera pertinent: Désolé pour l'indentation, il est pas si mal sur le texte Sublime

var Validator = function() { 
    this.elements = {}; 
    this.alerts = new Array(); 
} 

Validator.prototype = { 
    hookElement: function(elementid, name, options) { 
     if (options === "object" || options === undefined) { 
      if (typeof options === "object" || options === undefined) { 
       if (elementid != undefined || name != undefined) { 
        this.elements[name] = $('#'+elementid); 
        this.elements[name].name = name; 
        this.elements[name].options = options || { 
                         maxLength: 5, 
                         smallLength: 5, 
                         partner: undefined, 
                         regex: undefined, 
                         uppercase: undefined, 
                         lowercase: undefined 
                         }; 
        var that = this;                 
        $('#'+elementid).on('keyup', function(e) { 
         if (that.elements[name].val().length > that.elements[name].options.maxLength) { 
          that.alerts.map(function(x) { 
           if (x.name === name && x.option === 'maxLength') { 
            return true; 
           } else { 
            that.alerts.push({ 
            'alert': name + ' Cannot Be Greater Than ' + that.elements[name].options.maxLength, 
            'name': name, 
            'option': 'maxLength', 
            'visible': true 
           }); 
           } 
          }); 
         } else { 

         } 
        }); 

       } else { 
        return console.log('Missing Arguments'); 
       } 
      } else { 
       return console.log('Options argument must be an object please visit the API page.'); 
      }; 
     }; 
    }, 

    hookForm: function(elementid, alertid, options) { 
     var li = document.createElement('li'); 
     var ul = document.createElement('ul'); 
     ul.id = 'alertsList'; 
     if (document.getElementById(ul.id) === null) { 
      document.getElementById(alertid).appendChild(ul); 
     } 

     var alertsExist = []; 
     var that = this; 
     if (elementid != undefined) { 
      $('#'+elementid).on('keyup', function() { 
       console.log(that.alerts); 
       for (var i = 0; i < that.alerts.length; i++) { 
        if (alertsExist.indexOf(that.alerts[i].name + ' ' + that.alerts[i].alert) === -1) { 
         li.id = that.alerts[i].name + that.alerts[i].option; 
         li.innerHTML = that.alerts[i].alert; 
         document.getElementById('alertsList').appendChild(li); 
         alertsExist.push(that.alerts[i].name + ' ' + that.alerts[i].alert); 
        } 
       } 
      }); 
     } 
    } 
} 

var test = new Validator(); 
test.hookElement('userEmail', 'Email'); 
test.hookElement('userPassword', 'Password'); 
test.hookForm('createForm', 'alerts'); 

Répondre

2

Vous utilisez la Array.prototype.map fonctionne d'une manière qui n'est pas destinée. Le rappel ne sera appliqué que sur les éléments du tableau, donc en effet, il ne se déclenchera pas sur un tableau vide. En plus de cela, vous manipulez le tableau que vous mappez à l'intérieur de votre callback, ce qui est une mauvaise idée.

Vous devez utiliser Array.prototype.find (plus d'informations: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) pour voir si l'élément est déjà dans la matrice, et si ce n'est pas le cas, faites votre logique that.alerts.push.

Edit: code: (non testé)

$('#'+elementid).on('keyup', function(e) { 
    if (that.elements[name].val().length > that.elements[name].options.maxLength) { 
     if (!that.alerts.find(function (x) { 
      return x.name === name && x.option === 'maxLength'; 
     })) { 
      // Item not yet in the array, so push it 
      that.alerts.push({ 
       'alert': name + ' Cannot Be Greater Than ' + that.elements[name].options.maxLength, 
       'name': name, 
       'option': 'maxLength', 
       'visible': true 
      }); 
     } 
    } 
}); 
Questions connexes