对不起,我的头衔没有意义。我会在这篇文章中尝试更好地解释:)我理解我的问题,找到了解决方案,但是我不觉得这是个好方法,所以我想提出一些建议。
我的工作流程:
我的问题:当我第一次单击该表单时,它运行良好,并且创建了一个新用户。但是,当我尝试注册第二个用户时,由于与前一个用户对象一起发送的id,他发出了一个PUT请求。
我理解为什么看到代码时是因为在视图的初始化函数中初始化了用户模型。(在外面之前)
这是我的看法:
define(['backbone',
'views/notification/form',
'models/form',
'text!templates/user-form.tpl'],
function(Backbone,
NotificationForm,
User,
FormTpl) {
var UserForm = Backbone.View.extend({
el: "#user-form",
template: _.template(FormTpl),
initialize: function() {
this.model = new User();
this.model.on("invalid",this.showErrors, this);
this.model.on('request',this.ajaxStart, this);
this.model.on('sync',this.ajaxComplete, this);
},
events: {
submit: 'register'
},
render: function() {
this.$el.html(this.template());
},
register: function(e) {
e.preventDefault();
var attrs = {
counter: 0,
created: new Date(),
updated: new Date(),
stackexchangeId: $('#stackId').val(),
site: $('#site').find(":selected").text()
};
var self = this;
this.model.save(attrs,
{
wait:true,
success: function(model, response) {
console.log('success ajax');
console.log(model);
console.log(response);
self.collection.add(model);
//self.collection.add(new User(response));
var form = { id:'#user', messages: 'User has been registered' };
var success = new NotificationForm({ type: 'success', form: form} );
success.closeSuccessNotification();
},
error: function(model, xhr, options) {
self.ajaxComplete();
if(xhr.status == '500') {
var form = { id:'#user', messages: 'Connection StackExchange API failed' };
} else {
var response = JSON.parse(xhr.responseText);
var form = { id:'#user', messages: response.users };
}
new NotificationForm({ type: 'warning', form: form} );
}
}
);
},
showErrors: function(errors) {
var form = { id:'#user', messages: errors.validationError };
new NotificationForm({ type: 'error', form: form} );
},
ajaxStart: function() {
this.$('#spinner-register').addClass('spinner-anim');
},
ajaxComplete: function() {
this.$('#spinner-register').removeClass('spinner-anim');
}
});
return UserForm;
因此,当我第二次单击时,我的模型是相同的,并且ID在这里。
我找到了一种解决方案,但我不觉得这是一个好方法,因为我必须将事件从initialize函数中移出。所以我创建了:
test: function(model) {
model.on("invalid",this.showErrors, this);
model.on('request',this.ajaxStart, this);
model.on('sync',this.ajaxComplete, this);
},
并在注册时注明:
register: function(e) {
this.model = new User();
this.test(this.model);
e.preventDefault();
etc.
}
它工作正常,但我完全删除了初始化函数,听起来不太好。我想像第一个示例一样保留初始化,并始终拥有一个新的User模型。谢谢 :)
您可以model.clear()
用来使模型像新的一样新鲜,然后在save()
POST请求上将被发送。
...
this.model.clear();
this.model.save(attrs,
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句