2016-03-26 19 views
4

私はこの非同期呼び出しを一般的な分度器とjavascriptの場所で使っています。分度器:要素のIDを取得

私は分節器のユーティリティメソッドを作成して、関連するdivのグループと入力テキストボックスの特定のDOMプロパティを単純にチェックしています。これは、私が取り組んでいる検証フレームワークのためのものです。アイデアはこのメソッドに分度子要素を渡し、その要素のIDに基づいて、関連するdivと入力テキストボックス上の特定のDOMプロパティを調べることです。これは、私はそれが動作するようになった方法です:

/** 
* Checks for error in a NUAF field 
* @param {String or Element} field . 
* @param {string} errorText expected validation error text to appear in tooltip 
*/ 
exports.checkForError = function (field, errorText) { 

    var innerCheck = function(fieldId) { 
     expect(fieldId).not.toBe(undefined); 
     var elmntd = element(by.id('divInput.'+fieldId)); 
     expect(elmntd).not.toBe(null); 
     expect(elmntd.getAttribute('tooltip')).toContain(errorText); 
     expect(exports.hasClass(element(by.id('prnt.'+fieldId)), 'has-error')).toBe(true); 
    }; 

    // this unbelievably complex block of code gets the id of the 
    // field argument. If string was passed, the fieldid is just that . 
    if (typeof field === 'string') { 
     innerCheck(field); 
    } else { 
     //what used to be field.id now needs 6 lines of code? 
     field.getAttribute('id').then(
      function(idAttribute) { 
       console.log("*********: "+idAttribute); 
       innerCheck(idAttribute); 
      } 
     ); 
    } 
}; 

質問は次のとおりです。コードのfield.getAttribute('id').thenブロックを書き込むためのより良い、より少ない冗長方法はあります。要素のIDを取得するためにこれをすべて書くだけのことは残念です。

+0

だけで簡単であるべきクラスのチェックをより読みやすくすることができます - hasClassヘルパーの代わりに、[custom toHaveClass matcher](http://stackoverflow.com/a/32699366/771848)を作成してください。 – alecxe

答えて

3

これは、あなたが直接約束に機能innerCheckを渡すことができます考慮に入れる場合は特に...非同期コードのためにその冗長ではありません。

// this unbelievably complex block of code gets the id of the 
// field argument. If string was passed, the fieldid is just that . 
if (typeof field === 'string') { 
    innerCheck(field); 
} else { 
    field.getAttribute('id').then(innerCheck); 
} 

あなた

関連する問題