내 백본 응용 프로그램에서 매개 변수로 몇 가지 하위 모델로 구성된 모델이 있습니다.가져 오기/저장 후 백본 서브 모델 업데이트
그래서 그것을 정의 가져 와서 저장할 때
app.Models.Account = Backbone.Model.extend({
initialize : function() {
this.set({
info : new app.Models.Info(),
logins : new app.Collections.Logins(),
billing : new app.Models.Billing(),
});
}
});
문제입니다. 예를 들어 가져올 때 JSON 응답은 info
에 대한 객체, logins
에 대한 배열 및 billing
에 대한 객체를 포함합니다. 백본은 자동으로 하위 매개 변수를 일반 매개 변수로 지정하므로 하위 모델이 단순 개체로 대체됩니다.
내 현재의 솔루션과 같이 모델의 fetch
메소드를 오버라이드 (override)하는 것입니다
fetch: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
resp = model.parse(resp, xhr);
model.get('info').set(resp.info);
model.get('logins').reset(resp.logins);
model.get('billing').set(resp.billing);
if (success) success(model, resp);
};
options.error = Backbone.wrapError(options.error, model, options);
return (this.sync || Backbone.sync).call(this, 'read', this, options);
}
그러나 이것은 단지 가져 오기위한 것입니다. save()
메서드를 호출 할 때 생성 된 모델의 업데이트 된 상태가 반환되므로 save()
메서드를 재정의해야합니다.
이 문제를 해결하기위한 좋은 방법이 있습니까?
set()
메서드를 재정의하는 것이 효과적 일 수 있지만 백본 코드베이스에서 벗어나기 시작했다는 것을 두려워 할 수 있습니다.
나는 또한 이미 업데이트 하위 모델에 대한 참조를 만들 것 때문에
parse : function (response) {
this.model.get('info').set(response.info);
response.info = this.model.get('info');
this.model.get('logins').reset(response.logins);
response.logins = this.model.get('logins')
this.model.get('billing').set(response.billing);
response.billing = this.model.get('billing');
return response;
}
같은 구문 분석 방법을 사용하는 방법에 대한 생각했다.
'this.model.get ('info ')와 같은주의 사항이 하나 있습니다. set (response.info); response.info = this.model.get ('info');'그게'x = m.get ('p'); x.set (...); m.set ('p', x)'는 "change"이벤트를 트리거하지 않습니다 (http://stackoverflow.com/a/13369672/479863의 후반부 참조). 하지만 당신의'parse '문제가 될 것이다. –
이벤트가 서브 모델에 바인딩되어 있다면 어떻게 동작하는지 테스트해야합니다. 어쨌든 부모 모델에서 이벤트를 변경하지 않고도 모든 것을 함께 구성하고 ajax 요청 (백본 동기화 사용)을 사용하기 때문에 살 수 있습니다. – Daniel