我正在开发一个请求和响应有效负载都被命名空间的项目。例如:
{
'SourceMachine':{
'Host':'some value',
'Description':'some value',
'UserName':'some value',
'Password':'some value'
}
}
为了能够在各个字段上执行 get() 和 set(),我在“source_model”中覆盖了 parse 方法,如下所示:
parse : function(response, xhr) {
return response.SourceMachine;
}
这一切都很好。但问题是:当我想做一个 POST 或 PUT 操作时,我必须将 Host、Description、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;
}
})
});