backbone Model调用save方法的时候提交方式
horizon使用的是backbone框架,但是我们的后台api都是只接收post请求,请求的路径为/api/,根据backbone的官档解释:
backbone的model.save方法会判断当前的model对象是否存在存在服务器中,如果存在服务器中,则调用"update" (HTTP PUT), 如果不存在,则调用"create" (HTTP POST), 判断的依据即为当前的model的属性'id'是否存在。
举例如下:
var UpdateAgentV = ModalView.extend({ initialize: function(data) { this.model = new UpdateAgentM(); this.setDefault(); this.defaults.id = 'edit-agent'; this.defaults.header = translate('operations.edit'); this.renderModal(); this.model.bind('change', this.render, this); this.model.set({ agents_id: data.project_id }); this.getAgent(data.project_id); }, getAgent: function(project_id){ var $this = this; this.ajaxRequest({ action: 'GetAgentsDetail', project_id: project_id }, function(res){ $this.model.set({ account_bank: res.data.account_bank, account_name: res.data.account_name, account_number: res.data.account_number, url: res.data.url, logo: res.data.logo, company: res.data.company, }); }); }, render: function() { tpl = _.template($("#template-edit-agent").html()); this.defaults.body = tpl(this.model.toJSON()); this.$el.html(this.template(this.defaults)); $('.modal-dialog').draggable({ handle: "div.modal-header" }); return this; }, }); var UpdateAgentM = ModalModel.extend({ defaults: { action: 'UpdateAgents', agents_id: '', account_bank: '', account_name: '', account_number: '', url: '', logo: '', company: '', }, initialize: function() { this.validator(); }, validator: function() { $("#edit-agent").find("form").validate({ rules: { account_bank: { required: true }, account_name: { required: true }, account_number: { required: true }, url: { required: true }, logo: { required: true }, company: { required: true }, } }); }, create: function(element) { var data = this.formSerialize(element); this.set(data); this.saved(agentsView); } });
上例中若将UpdateAgentV的initialize的this.model.set({agents_id: data.project_id});改为this.model.set({id: data.project_id});, 则在model调用save方法时则会认为当前的model已经存在,提交数据就会用PUT方法。