API를 사용하여 데이터베이스에 저장하는 모델이 있습니다. 내 문제는이 모델을 업데이트 할 때입니다. 처음으로 무엇인가를 변경하고 model.save를 호출하면 속성이 JSON으로 전달되어 API를 파싱하고 문제없이 저장합니다. 이제 같은 뷰에서 두 번째로 해당 모델을 변경하면 model.save가 정의되지 않은 객체를 내 모델에 추가합니다. API는이 객체를보고 PUT 요청을 거부합니다.Backbone.js RESTful API 관련 문제
왜 두 번째 업데이트가 아닌 첫 번째 업데이트에서 작동합니까?
도와 주셔서 감사합니다.
여기 코드는 이해할 수 있기를 바랍니다. 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
모델 코드 및 저장 방법을 추가하십시오. –