我怎样才能正确地贯彻执行中的骨干模型解析,包括收藏? [英] How can I correctly implement parse in a Backbone model to include collections?
问题描述
我有一个名为会员骨干模型
- 这包含了会员的数据,如姓,名,电子邮件,电话等,还包括多值字段我需要保持为集合 - 这是度
和兼职
I have a backbone model called Member
- this contains membership data such as first name, last name, email, phone, etc. It also includes multi-valued fields that I need to keep as collections - these are Degrees
and Affiliations
.
我运行的问题调用在我的模型的取()
方法时,到的是,有一个基本的阵列之间各种各样的阻抗失配,以及集合对象我在我的模型。由于解析
顾名思义应该返回一个哈希中使用设置
,而不是实际的设定值,这是不可能的对我来说,把我收藏这条路。例如 - 如果我返回度的JavaScript对象
,看起来像下面这样: {度:[{ID:1,标题:博士}]}
,然后这是我的度
集合转换成一个平面数组。这里是我的code:
The issue I am running into when calling the fetch()
method in my model is that there's an impedance mismatch of sorts between a basic array, and the collection objects I have in my model. Since parse
by definition is supposed to return a hash to be used in set
rather than actually setting values, it is impossible for me to set my collections this way. For instance - if I return a JavaScript object for Degrees
that looks something like the following: {degrees: [{id: 1, title: "PhD"}]}
, then this converts my degree
collection into a flat array. Here is my code:
window.Models.Member = Backbone.Model.extend({
url: '/api/member',
initialize: function() {
_.bindAll(this);
this.set('degrees', new window.Collections.DegreesList());
this.fetch();
},
parse: function(response) {
var setHash = {};
setHash.first_name = response.first_name;
setHash.last_name = response.last_name;
setHash.office_phone = response.office_phone;
// When this is run, this.get('degrees') will now return a flat array rather than a DegreesList collection
setHash.degrees = _(response.degrees).each(function(item) {
return {id: item.id, title: item.title}
});
return setHash;
}
});
我可以手动设置我的解析函数的集合,但似乎像它颠覆主干路,哈克。
I could manually set the collections in my parse function, but that seems like its subverting the Backbone way, and hacky.
编辑:我暂时这样做解决了这个问题如下:
I've temporarily solved the problem by doing the following:
parse: function(response) {
var setHash = {};
setHash.first_name = response.first_name;
setHash.last_name = response.last_name;
setHash.office_phone = response.office_phone;
this.get('degrees').reset( response.degrees );
return setHash;
}
我怀疑这是最佳的解决方案,但它肯定适用于现在。我接受更好的建议。
I doubt this is the optimal solution, but it certainly works for now. I'm open to better suggestions.
推荐答案
我用的正是你所提议,除了有一些变化相同的解决方法。
I use exactly the same workaround you are proposing except with a few changes.
- 要避免误解我所说的JSON集合:
degreesData code>
- 在
初始化
我创建这样的集合:this.degrees =新度()重置(this.get(degreesData ));
- To avoid misunderstanding I call the collection in the JSON:
degreesData
- In the
initialize
I create the collection like this:this.degrees = new Degrees().reset( this.get( "degreesData" ) );
这篇关于我怎样才能正确地贯彻执行中的骨干模型解析,包括收藏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!