我正在验证模型的属性(名称),为了确保客户必须在注册表中输入他们的名字。
查看:
define(["jquery" ,
"underscore" ,
"backbone" ,
"text!templates/CustomerTemplate.html",
"models/Customer"
],function($ , _ , Backbone, CustomerTemplate, CustomerModel){
var CustomerView = Backbone.View.extend({
initialize : function(){
this.listenTo(this.model, 'change', this.render);
},
events : {
'submit #customerForm' : 'Customer'
},
Customer : function(e){
e.preventDefault()
var _customer = new CustomerModel({
UID: "00000000-0000-0000-0000-000000000000",
Sex: 0,
Name: $("#name").val(),
});
this.model.save(_customer,{validate: true},{
wait:true,
success:function(model, response) {
console.log('Successfully saved!');
},
error: function(model, error) {
console.log(model.toJSON());
console.log('error.responseText');
}
});
},
render : function(){
var customertemplate = _.template(CustomerTemplate);
this.$el.html(customertemplate(this.model.toJSON()));
return this;
}
});
return CustomerView;
});
型号:
define(["underscore" , "backbone"],function(_ , Backbone){
var CustomerModel = Backbone.Model.extend({
urlRoot: "myurl",
initialize : function(){
this.bind('invalid', function(model, error) {
console.log(error);
});
},
validate: function (attrs){
if ( !attrs.Name) {
return 'You must provide a name';
}
},
defaults : {
UID: "00000000-0000-0000-0000-000000000000",
Sex: 0,
Name: "",
}
});
return CustomerModel;
});
问题:即使属性Name
不是null
,validate
方法中的错误消息仍会显示(You must provide a name
)。
任何可能导致这种情况的想法都是值得欣赏的。感谢。
答案 0 :(得分:1)
当您在CustomerView中调用this.model.save
时,您将向其传递一个您在前一个语句中实例化的新Customer
模型。这不是你想要的;您要么致电_customer.save()
以保存全新的模型,或者 - 更有可能 - 您希望将新属性传递给现有模型,并保存:
var newAttrs = {
UID: "00000000-0000-0000-0000-000000000000",
Sex: 0,
Name: $("#name").val(),
};
this.model.save(newAttrs);
当您在现有代码中调用this.model.save(_customer, {validate: true})
时,Customer
模型会传递到您的validate()
函数。该模型没有Name
属性。它 具有Name
属性 - 您可以通过_customer.get('Name')
访问它 - 但您应该遵循Backbone惯例并假设您的验证方法变得简单& #39; JavaScript对象,而不是Backbone模型。