요청 및 응답 페이로드가 모두 네임 스페이스 인 프로젝트에서 작업하고 있습니다. 예를 들어 : 잘 있어요 그Backbone.js에서 이름 공간 페이로드로 작업하기
parse : function(response, xhr) {
return response.SourceMachine;
}
:
{
'SourceMachine':{
'Host':'some value',
'Description':'some value',
'UserName':'some value',
'Password':'some value'
}
}
이 (수) 개별 필드에()를 설정 할 수 있으려면, 정말처럼 내 "source_model"의 구문 분석 방법을 오버라이드 좋은. 하지만 문제는 이것입니다 : POST 또는 PUT 작업을 수행하려면 호스트, 설명, UserName 및 Password 특성을 SourceMachine 네임 스페이스에 가져와야합니다.
var tempAttributes = this.model.attributes;
this.model.clear();
this.model.save({SourceMachine: tempAttributes});
이 작동하지만, KLUGE의 비명 : 기본적으로 내가 모델을 복사하는 일을 봤는데 다음과 같이 저장 모델을 삭제, 임시 객체에 속성! 네임 스페이스 데이터로 작업하는 더 좋은 방법이 있어야합니다. 감사!
그들은 모두 네임 스페이스 데이터에 의존하기 때문에 지금, 나는 내 응용 프로그램의 모든 모델에 사용됩니다 기본 모델의 require.js 모듈을 만든
업데이트 :
define(function() {
return Backbone.Model.extend({
/**
* Adding namespace checking at the constructor level as opposed to
* initialize so that subclasses needn't invoke the upstream initialize.
* @param attributes
* @param options
*/
constructor : function(attributes, options) {
//Need to account for when a model is instantiated with
//no attributes. In this case, we have to take namespace from
//attributes.
this._namespace = options.namespace || attributes.namespace;
//invoke the default constructor so the model goes through
//its normal Backbone setup and initialize() is invoked as normal.
Backbone.Model.apply(this, arguments);
},
/**
* This parse override checks to see if a namespace was provided, and if so,
* it will strip it out and return response[this._namespace
* @param response
* @param xhr
* @return {*}
*/
parse : function(response, xhr) {
//If a namespace is defined you have to make sure that
//it exists in the response; otherwise, an error will be
//thrown.
return (this._namespace && response[this._namespace]) ? response[this._namespace]
: response;
},
/**
* In overriding toJSON, we check to see if a namespace was defined. If so,
* then create a namespace node and assign the attributes to it. Otherwise,
* just call the "super" toJSON.
* @return {Object}
*/
toJSON : function() {
var respObj = {};
var attr = Backbone.Model.prototype.toJSON.apply(this);
if (this._namespace) {
respObj[this._namespace] = attr;
} else {
respObj = attr;
}
return respObj;
}
})
});
매우 좋습니다. 나는 이것을 할 수있는 쉬운 방법이 있다는 것을 알고있었습니다. 당신은 이것을 다루는 몇 가지 훌륭한 방법을 제시했습니다! 감사! –
이것은 'toJSON'과 같은 함수를 호출하지 않으므로 PUT 메소드에서는 작동하지만 PATCH 메소드에서는 작동하지 않습니다. – Kevin
@kevin : Patch에 대해 알아 냈습니까? 요즘에는 백본을 적극적으로 사용하지 않기 때문에 최선의 접근 방법이 내 머리 꼭대기에서 벗어날 수 있을지 잘 모르겠습니다. –