我试图根据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
所以当()不候。我究竟做错了什么?
你怎么调用使用'$ .when'的方法? – tkone
在视图中我执行:this.model.isValid(),这会导致骨干模型中的validate函数被执行。如果它没有返回任何内容,那么它是有效的,如果它返回一些东西,那么它就是无效的...... – user1716672