APIを使用してデータベースに保存するモデルがあります。私の問題は、このモデルを更新するときです。私が何かを変更してmodel.saveを呼び出すと、その属性はJSONとしてapiに渡され、apiはそれを解析して問題なく保存します。今度は、同じビューでそのモデルを2回目に変更すると、model.saveは未定義のオブジェクトをモデルに追加します。 apiはこのオブジェクトを参照し、PUT要求を拒否します。Backbone.js RESTful APIで問題が発生する
なぜ最初のアップデートで動作し、2番目のアップデートで動作しないのですか?
ありがとうございます。
ここにコードがあります。私はあなたがそれを理解できることを願っています。 model.saveにすべての引数を渡す
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
モデルのコードと保存方法を追加してください。 –