我有一个模型,我使用api保存到数据库。我的问题是更新这个模型。我第一次改变任何东西并调用model.save时,这些属性作为JSON传递给api,解析并保存它,没有问题。现在,第二次在同一视图中对该模型进行更改时,model.save将未定义的对象添加到我的模型中。 api看到这个对象并拒绝PUT请求。Backbone.js model.save()问题与RESTful api
为什么它能在第一次更新时使用,而不是第二次使用?
感谢您的帮助。
这是代码,我希望你能理解它。
var LDAccount = Backbone.Model.extend({
defaults : {
ACC_NUM : '',
BOOK_DATE : '',
F_NAME : ''
},
template : _.template(
"<p>Full Name</p><input data-id='F_NAME' type=text value='<%= F_NAME %>' />" +
"<p>Book Date</p><input data-id='BOOK_DATE' type=text value='<%= BOOK_DATE %>' />"
),
urlRoot : 'api/account'
});
var LDAccountView = Backbone.View.extend({
el : '', // set this when instantiating this model in the router
initialize : function(options) {
this.model = options.model;
this.model.id = options.id;
this.model.bind('change', this.render, this);
this.model.bind('error', this.renderError, this);
},
render : function() {
$(this.el).html(this.model.template(this.model.toJSON()));
$(this.el).append(
'<div id="model_buttons" >' +
'<input type=button id=reset value=Reset />' +
'<input type=button id=save value=Save />' +
'</div>'
);
return this;
},
events : {
'click #save' : 'save2db'
},
save2db : function() {
var $fields = $(this.el).find('input[type=text]');
var modObj = new Object();
$fields.each(function() {
var $field = $(this);
var prop = $field.attr('data-id');
var val = $field.val();
modObj[prop] = val;
});
this.model.set(modObj);
console.log(modObj);
this.model.save({
success : function() {
self.reset();
}
});
return false;
},
renderError : function() {
$(this.el).append('<p class=error>Account does not exist</p>');
},
reset : function() {
}
});
var MainView = Backbone.View.extend({
// code omitted since it's not relevant to the question
});
var LDRouter = Backbone.Router.extend({
routes : {
"account/:modl/:acc_num": "renderView"
},
initialize : function() {
this.search = new MainView({ el : '#main'});
},
// THIS IS THE VIEW THAT RENDERS THE MODEL
renderView : function(modl, acc_num) {
var self = this;
var model = null;
switch(modl) {
case 'account':
model = new LDAccount();
break;
// these other models were omitted for clarity
case 'asset':
model = new LDAsset();
break;
case 'info':
model = new LDInfo();
break;
default:
model = new LDAccount();
break;
}
this.account = new LDAccountView({ id : acc_num, el : '#accDetail', model : model });
this.account.reset = function() {
self.renderView(modl,acc_num);
};
this.account.model.fetch();
},
accountInfo : function (acc_num) {
var root = '';
var url = window.location.href;
var hashPos = url.indexOf('#');
if(hashPos != -1) {
root = url.substr(0,hashPos);
} else {
root = url;
}
window.location = root + "#account/account/" + acc_num;
}
});
$(function() {
var app = new LDRouter();
Backbone.history.start();
});
添加一些示例代码以提供关于您正在做的事情的额外信息真的有帮助。 – ryanmarc 2012-01-17 05:44:27
请添加模型的代码以及如何保存它。 – 2012-01-17 06:51:46