1

请帮我 :)

我有骨干模型:

var people = Backbone.Model.extend({
...
parse : function() {

  return response
}
})

并收集:

var group = Backbone.Collection.extend({
model: people
...
})

通常我通过调用集合同步方法获取数据,但有时我调用模型获取方法。

我的后端返回格式为:

{code: 0, data: {'1': {name: 'alex'}, '2': {name: 'max'}}}

问题:如果我为处理我的后端答案编写模型解析方法 - 集合同步不起作用(因为服务器答案有另一种格式),如果我为集合编写解析方法 - 不要进行后端处理。

我如何创建通用处理?

我找到了方法,查看 parse 方法中的选项并使用 else/if,但我不喜欢它。

4

2 回答 2

-1

Here's how I do it in mine (I have a lot of nested data and have to map existing objects to my views to ensure my view is updated without complete refresh):

//pass {parse: true} if Person has nested data that needs parsing as well

parse: function(response, xhr) {
                for(var key in this) {
                    if (key === 'person') {
                        var embeddedClass,
                            embeddedData = response[key], 
                            exsiting = this.get(key);

                       if (existing == null) {

                            embeddedClass = new Person(embeddedData, {parse: true}); 
                       } else {
                            existing.set(key, existing.parse(embeddedData));
                            embeddedClass = existing
                       } 
                       response[key] = embeddedClass;
                    }
                }
                return response;
            }

then when the new data comes and I need to parse it again manually, I call

this.set(this.parse(response));
于 2014-02-05T18:36:31.573 回答
-1

选项1:

使用额外的 _PeopleBase 类会有帮助吗?

var _PeopleBase = Backbone.Model.extend({
    ...
})
var people = _PeopleBase.extend({
...
parse : function() {

  return response
}
})

收藏:

var group = Backbone.Collection.extend({
model: _PeopleBase
...
parse : function() { //Collection parser


  return response
}

})

选项 2: 如果可能,您可以依赖返回的数据来决定如何解析它

parse : function(response, options) { 
  //Test the response with whichever way you can definitely differentiate them

  return response
}

选项 3: 取决于谁是 parse 函数的调用者:

parse : function(response, options) { 
    if (this instanceof People) {

    } else {

    }

  return response
}

希望这有帮助!

于 2013-08-12T18:38:04.313 回答