在Backbone.js中使用名称空间的有效负载
我正在从事一个项目,其中请求和响应有效负载都是命名空间的。例如:在Backbone.js中使用名称空间的有效负载,backbone.js,Backbone.js,我正在从事一个项目,其中请求和响应有效负载都是命名空间的。例如: { 'SourceMachine':{ 'Host':'some value', 'Description':'some value', 'UserName':'some value', 'Password':'some value' } } 为了能够对各个字段执行get()和set(),我在“source_model”中重写了parse方法,如下所
{
'SourceMachine':{
'Host':'some value',
'Description':'some value',
'UserName':'some value',
'Password':'some value'
}
}
为了能够对各个字段执行get()和set(),我在“source_model”中重写了parse方法,如下所示:
那很好。但问题是:当我想执行POST或PUT操作时,我必须将主机、描述、用户名和密码属性放入SourceMachine名称空间。基本上,我一直在做的是将模型属性复制到临时对象,清除模型,然后按如下方式保存:
var tempAttributes = this.model.attributes;
this.model.clear();
this.model.save({SourceMachine: tempAttributes});
这是可行的,但它叫克鲁格!必须有更好的方法来处理命名空间数据。谢谢
更新
我现在为一个基本模型创建了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
model.toJSON()
返回用于JSON字符串化的模型属性副本。这可以用于持久化、序列化或在移交给视图之前进行扩充
您可以提供自己的toJSON
:
toJSON: function() {
return { SourceMachine: _(this.attributes).clone() };
}
这应该会让你的服务器满意。不幸的是,toJSON
也常用于为模板提供数据,您可能不希望SourceMachine
噪音出现;如果是,则添加另一种方法来为模板准备数据:
// Or whatever you want to call it...
valuesForTemplate: function() {
return _(this.attributes).clone();
}
这就是标准的
toJSON
方法在内部的作用。非常酷。我知道有一个简单的方法可以做到这一点。你已经给出了一些很好的处理方法!谢谢这适用于PUT方法,但不适用于PATCH方法,因为它不调用任何函数,比如toJSON
。@kevin:你找到补丁的方法了吗?最近我没有积极地使用主干网,所以我不确定最好的方法是什么。@muistooshort重写save()
函数似乎对PATCH方法有效。
// Or whatever you want to call it...
valuesForTemplate: function() {
return _(this.attributes).clone();
}