2016-05-12 4 views
0

(例として)私の設定はそうのような設定です:動的要素を関数にバインドする。一つだけバインドを残し

this.config = [ 
    { 
     element: '#Amount', 
     type: "money", 
     notNull: true, 
     error: "You must specify an amount" 
    }, 
    { 
     element: '#Type', 
     type: "string", 
     notNull: true, 
     error: "You must specify whether you want a 6 week loan or a 12 month loan" 
    } 
] 

私は、リスト内の各要素にバリデーション機能をバインドするバインド機能を持っている:

this.bind = function() { 
    for (var i = 0; i < _this.config.length; i++) { 
     var arr = _this.config[i]; 
     console.log('Binding ' + arr.element + ' to single input validation') 
     // bind single validation to each element 
     $(document).on('keyup', arr.element, function() { 
      _this.validate(arr.element) 
     }) 
    } 
} 

とコンソールに私が提示しています:

Binding #Amount to single input validation 
Binding #Type to single input validation 
Binding #LoanPurpose to single input validation 

設定は、実際に47個の要素から構成され、しかし私は、最後のバインドが残っていることを確信していますそれは前回のバインドを毎回置き換えているかのようになります。

任意のポインタを大幅にこれは古典的なjavascriptのエラーです

おかげ

答えて

3

をいただければ幸いです。ネストされたkeyupハンドラ関数は、arrという変数を参照します。これは、繰り返しごとにforループによって上書きされています。したがって、keyupハンドラが最後に実行されるとき、arrthis.config配列の最後の要素を参照しています。

このリンクはwhy it's bad to make functions within loopsを説明しています。そしてそれに対する解決法を提供します。

はここにあなたのコードは、おそらくどのように見えるべきかです:

this.bind = function() { 
    for (var i = 0; i < _this.config.length; i++) { 
     var arr = _this.config[i]; 
     console.log('Binding ' + arr.element + ' to single input validation') 
     // bind single validation to each element 
     _this.makeBind(arr.element) 
    } 
} 

this.makeBind = function (el) { 
    $(document).on('blur', el, function() { 
     _this.validate(el) 
    }) 
} 
+0

への入力の現在値の両方を渡す直前いただきありがとうございますあなたの答え – zanderwar

0
config.forEach(function(item) { 
    $(document.body).on('keyup', item.element, function() { 
    validate(item, this.value) 
    }); 
}); 

あなたが好きな何かを行うことができます項目、および検証機能

関連する問題