2017-03-14 4 views
0

나는 길을 잃어 버렸고 정확히 무엇을보아야할지 확실하지 않습니다. jQuery와 관련이 있다는 것을 알고 있습니다. 그래서, 요점은, 나는 이메일이 유효한지 여부를 확인하기 위해 부울로 "통과"변수를 반환하려고 노력하고있어. value = "asdf"로 false를 전달하는 대신 true를 계속 전달합니다. 나는 그것이 비동기 요청 때문에, 나는 그 변수를 연기하는 방법을 정확하게 모르겠다는 것을 안다. 코드는 다음과 같습니다.

console.log(this.newValidate($('#forgottenPwdForm'))); // Returns true 

newValidate: function(form){ 
    var $form = form, 
     errmsg = function(msg){ 
      return '<span class="error" style="text-align:right; margin: 2px 15px; color:red;">' + msg + '</span><br/>'; 
     }; 

    // Check email/username 
    // Needs to run 2 validations. Is the email valid? And is it duplicate if valid 
    if($form.find('.email').length) 
     $form.find('.email').each(function(){ 
      var email = escape($(this).val().trim()), 
       valid = true, 
       duplicate = false, 
       pass = true; 

      // Check if email is valid 
      $.when(
       $.get('/service/account/ajaxdata?method=validemail&emailaddr='+email, function(res){ 
        console.log(res); 
        valid = res; 
       }), 

       $.get('/subscribe/check_email?email=' + email, function(data) { 
        if(data){ 
         duplicate = false; } 
       }) 

      ).then(function(){ 

       if(valid == 0){ 
        var error = errmsg("Email is not valid."); 
        pass = false; 
        console.log(pass); 
       } 
       else { 
        // Now that the email is valid, we need to check if it's duplicate 
        if(duplicate == false) { 
         $('.email').addClass('emailError'); 
         pass = false; 
        } 
        else { 
         if($('.email').hasClass('emailError')) { 
          $('.email').removeClass('emailError'); 
          $('.email').removeClass('error'); 
         } 

         pass = true; 
        } 
       } 

      }); 

      if(pass == false) return pass; 
     }); 

코드는 false를 반환해야 할 때 true를 반환합니다. 다시 말하지만 $ .get 요청과 변수가 범위를 벗어나는 것과 관련이 있다는 것을 알고 있습니다. 어떻게 지연 시킬지 잘 모르겠습니다.

+0

그것은 좋은 찾고 있었던이 줄'경우까지 (통과 == false)를 return pass;는 약속을 벗어나므로 먼저 실행됩니다. 당신은 단순히 "if (isvalid() == true)'타입 테스트를 할 때'isvalid()'가 ajax 호출을 할 때 (그러나 당신은 이미 그것을 알고 있다고 생각합니다.) 자세한 정보는 여기를 참고하십시오 : http : // stackoverflow .com/questions/14220321/how-do-i-return-as-asynchronous-call/14220323 –

+0

나는 그것을 이해하지만 newValidate 메소드는 전체 메소드가 실제로 더 많은 체크를하고있다. '.required'/ '.passwd'클래스를 검사하고 해당 통과 여부에 따라 false를 반환하며, false 반환은 양식이 게시되지 않도록합니다 (표시되지 않음). 현재 해당 링크를 확인하고 있습니다. – jamadri

답변

0

변수를 설정하는 대신 결과와 함께 콜백 메소드를 실행해야합니다.

코드가 비동기 적으로 실행되므로 유효성 검사 코드를 실행하지 않고 실행이 끝나면 바로 실행되므로 항상 사실입니다.

그래서 대신의 말을 패스 = TRUE | 당신은 같은 것을 할 필요가 거짓 MyCallBackFunction | newValidate() 내부

2

(참 거짓)를 사용하는 약속 때문에 약속을 반환 . 콜백 "because then you lose exception bubbling (the point of promises) and make your code super verbose"(@ Esailija)을 전달하려는 유혹을받지 마십시오. 다음과 같이

newValidate: function($form) { 
    var $emailElements = $form.find('.email'); 
    var promises = $emailElements.map(function(index, el) { // Use `.map()` to produce an array of promises. 
     var email = escape($(el).val().trim()); 
     return $.when(
      $.get('/service/account/ajaxdata?method=validemail&emailaddr=' + email), // no direct callback here ... 
      $.get('/subscribe/check_email?email=' + email) // ... or here. 
     ).then(function(valid, unique) { // Simple! The two $.get() responses appear hear as arguments. 
      // The question's `data` appears to be a `unique` indicator (ie !duplicate), but the sense may be reversed? 
      var pass = valid && unique; // A composite pass/fail boolean for this email element. 
      if(!pass) { 
       $(el).addClass('emailError'); 
      } else { 
       $(el).removeClass('emailError'); 
      } 
      // Note: It would be better to give the user separate indications of invalid|duplicate, so (s)he has a better clue as to what's wrong. 
      return pass; // whatever is returned here will be the value delivered by the promise inserted into the `promises` array 
     }); 
    }); 
    // Now use `$.when()` again to aggregate the `promises` array. 
    return $.when.apply(null, promises).then(function() { 
     // Now use `Array.prototype.reduce` to scan the arguments list (booleans) and give a composite pass/fail boolean. 
     var pass = Array.prototype.reduce.call(arguments, function(prev, current) { 
      return prev && current; 
     }, true); 
     if(!pass) { 
      return $.Deferred().reject(new Error(errmsg("At least one email is not valid."))).promise(); // jQuery's cumbersome way to `throw` an error from a promise chain. 
     } 
    }); 
} 

전화 :

이 따라서 의견을 많이, 약속에 상당히 도전적인 소개

this.newValidate($("#myForm")).then(function() { 
    // pass 
}, function(error) { 
    // Something went wrong. 
    // Expected error or unexpected error will end up here. 
    consoe.log(error); 
    $("#whatever").append('<div class="error">' + error.message + '</div>'); // if required 
}); 
+0

이것은 실제로 더 나은 설명입니다. 우선,이 설명을 쓸 시간을 줘서 고맙다고 말하고 싶습니다. 둘째, 이것은 내가 찾고 있었던 것을 분명히 나타내며, 단순히 code 나는 약속이 더 잘 작동하는 것을보고 있습니다. 다시 한번 감사드립니다! – jamadri