我在 Backbone 验证方面遇到了一些问题,但似乎我找到了正确的方法。我设法实现了以下目标:
var EditUser = Backbone.View.extend({
el:'.page',
validates:function(evt){
console.log('here');
var $field = $(evt.currentTarget);
if($field.val() === ''){
$field.css('border', '1px solid red');
return false;
}
else{
$field.css('border', '1px solid #ccc');
}
},
render: function(options){
var that = this;
if(options.id){
that.user = new User({id: options.id});
that.user.fetch({
success: function(user){
var template = _.template($('#edit-user-template').html(), {user:user});
that.$el.html(template);
}
});
} else{
var template = _.template($('#edit-user-template').html(), {user:null});
this.$el.html(template);
}
},
events: {
'keyup input[name=firstname], input[name=lastname], input[name=age]': 'validates',
'submit .edit-user-form': 'saveUser',
'click .delete': 'deleteUser'
},
saveUser: function (ev){
this.$('input[type=text]').each(function() {
$(this).trigger('keyup');
});
var userDeatils = $(ev.currentTarget).serializeObject();
var user = new User({validate:true});
user.save(userDeatils,{
success: function(user){
router.navigate('', {trigger:true});
}
})
return false;
},
deleteUser: function(ev){
this.user.destroy({
success: function(){
router.navigate('', {trigger:true});
}
});
return false;
}
});
当我开始在输入字段中输入时一切正常,但是当我提交表单时我需要执行相同的操作。(已经附加了一个 saveUser )。我需要找到一种运行验证蚂蚁的方法,在调用“saveUser”之前停止以空详细信息提交的表单