2014-03-25 83 views
0

我试图根据Backbone.js中的国家/地区代码验证电话号码。我需要等到ajax回调被执行之后才返回验证结果。我正在使用Jquerys when方法。该模型的验证功能:Jquery .when()不等待

validate: function(attrs) { 

     this.errors = []; 


     if(attrs['phone'].length>0){ 
      //validate 

      console.log('before when '); 

      $.when(this.checkPhoneNumber(attrs)).done(function(response){ 

       console.log('resspone is '); 
       console.log(response); 

       if(response.valid!==true){ 
        that.errors.push({input_tag: 'phone', error: 'Please enter a valid phone number'}); 
       } 

       if(that.errors.length > 0){     
        return that.errors; 
       } 

      }); 

      console.log('after when '); 


     } 
     else{ 

      console.log('in the else so no phone number'); 

      if(this.errors.length > 0){ 
       return this.errors; 
      } 
     } 

    },   

而且checkPhoneNumber是:

checkPhoneNumber: function(attrs){ 

      return $.ajax({ 
       url: "http://hidden-oasis-1864.herokuapp.com/check-phone-number/"+attrs['country']+"/"+attrs['phone'], 
       success: function(response){ 

        console.log('in checkPhoneNumber success'); 

       }, 
       error: function(){ 

        that.errors.push({input_tag: 'phone', error: 'There was an error validating the phone number'}); 
        return that.errors; 
       } 
      });  

    }, 

在视图中,我做的:

 if (!this.model.isValid()) {   
      this.processErrors(this.model.validationError); 
     } 

isValid()运行模型的validate()methos。

但在日志中我总是得到:

before when ContactModel.js:46 

after when ContactModel.js:63 

MODEL IS VALID ContactItem.js:66 

in checkPhoneNumber success 

所以当()不候。我究竟做错了什么?

+0

你怎么调用使用'$ .when'的方法? – tkone

+0

在视图中我执行:this.model.isValid(),这会导致骨干模型中的validate函数被执行。如果它没有返回任何内容,那么它是有效的,如果它返回一些东西,那么它就是无效的...... – user1716672

回答

2

尝试用

checkPhoneNumber: function(attrs){ 

     return $.ajax({ 
      url: "http://hidden-oasis-1864.herokuapp.com/check-phone-number/"+attrs['country']+"/"+attrs['phone'], 
      success: function(response){ 

       console.log('in checkPhoneNumber success'); 

      }, 
      error: function(){ 
       console.log("I FOUND MY PROBLEM"); 

       that.errors.push({input_tag: 'phone', error: 'There was an error validating the phone number'}); 
       return that.errors; 
      } 
     });  

}, 

它看起来像Ajax调用返回一个错误,所以done不会被调用。

要注册失败的回叫,请使用fail并注册回叫以始终执行使用then

+0

'then'回传通过/失败/通知,但总是执行。 – psquared

+0

但它进入成功,因为我看到“在checkPhoneNumber成功” – user1716672

+0

我可以得到这个值得的唯一方法是通过在ajax请求中包含选项async:false。它的作品。但似乎没有必要使用async:false选项与.when() – user1716672