所以我设置了一个新表单,它会临时保存,但我希望它只能在验证后才能更新,否则会显示一些错误。这是在 saveEdits 事件的视图部分关于我做错了什么的任何线索?
这是我的 main.js 文件
(function () {
window.App = {
Models: {},
Collections: {},
Views: {},
Templates: {},
Router: {}
};
// MODEL
App.Models.User = Backbone.Model.extend({
defaults: {
firstName: 'first',
lastName: 'last',
email: 'Email',
phone: '222',
birthday: '07/22/1980'
},
validate: function (attrs) {
if (!attrs.firstName) {
return 'You must enter a real first name.';
}
if (!attrs.lastName) {
return 'You must enter a real last name.';
}
if (attrs.email.length < 5) {
return 'You must enter a real email.';
}
if (attrs.phone.length < 10 && attrs.phone === int) {
return 'You must enter a real phone number, if you did please remove the dash and spaces.';
}
if (attrs.city.length < 2) {
return 'You must enter a real city.';
}
},
initialize: function() {
this.on('invalid', function (model, invalid) {
console.log(invalid);
});
}
});
//var userModel = new App.Models.User();
//VIEW
App.Views.User = Backbone.View.extend({
el: '#user',
//model: userModel,
//tagName: 'div',
//id: 'user',
//className: 'userProfile',
//template: _.template($("#userTemplate").html()),
//editTemplate: _.template($("#userEditTemplate").html()),
initialize: function (){
},
render: function() {
this.template = Handlebars.compile($("#userTemplate").html());
this.editTemplate = Handlebars.compile($("#userEditTemplate").html());
this.$el.html(this.template(this.model.toJSON()));
return this;
},
events: {
'click button.edit': 'editProfile',
'click button.save': 'saveEdits',
'click button.cancel': 'cancelEdits'
},
editProfile: function () {
this.$el.html(this.editTemplate(this.model.toJSON()));
},
saveEdits: function () {
var form = $(this.el).find('form#updateUser');
this.model.set({
firstName : form.find('.firstName').val(),
lastName : form.find('.lastName').val(),
email: form.find('.email').val(),
phone: form.find('.phone').val(),
birthday: form.find('.birthday').val()
});
this.model.validate();
this.render();
},
cancelEdits: function() {
this.render();
}
});
//start history service
Backbone.history.start();
var user = new App.Views.User({model: new App.Models.User()});
user.render();
})();
在我插入 this.model.validate 并显示错误之前它工作正常:
Uncaught TypeError: Cannot read property 'firstName' of undefined