【问题标题】:Backbone.js updating a Collection's model in the collectionBackbone.js 更新集合中的集合模型
【发布时间】:2014-12-28 03:58:20
【问题描述】:

我在组织几个月内传入 Backbone 模型的 JSON 时遇到了一些麻烦(我得到了一个空集合)。我试图尽可能明确,所以 Year Collection 实际上是这样设置每个参数的。

所以我有一个名为 Year 的 Backbone 集合,它是 Backbone 模型 Month 的集合,它又具有一个 events 属性,它是模型 Event 的集合。

$(function(){
var Event = Backbone.Model.extend({

});

var Events = Backbone.Collection.extend ({
    model: Event
});

var Month = Backbone.Model.extend ({
});

var Year = Backbone.Collection.extend ({
    model: Month,
    url: '/api/v1/calendar/2014'

});

window.Calendar = new Year();
var promise = Calendar.fetch();

promise.done(function(response){ 
    if ('events' in response) {
        console.log('Events found');
        response = response.events;

        // Cycle through events and add to Collection
        for (var i = 0; i < response.length; i++) {
            var currentMonth = response[i].startdate.split('-');

            thisEvent = new Event(response[i]);
            thisMonth = new Month({
                'name': currentMonth[1],
                'events': new Events(thisEvent)
            });

            Calendar.add(thisMonth);                  
            console.log('Set ' + currentMonth[1] + ' with Event ' + response[i]);

        }

    } else {
        console.error('Zero events');
    }
}).fail(function(response){ 
    console.error('Failed to fetch Calendar');
}); 
});

我传入的JSON很简单,是这样的

{
"status": "success",
"year": 2014,
"events": [
    {
        "title": "None",
        "startdate": "2014-01-23",
        "description": "Event Description"
    },
    {
        "title": "None",
        "startdate": "2014-01-25",
        "description": "Event Description 2"
    }
]
}

我不太清楚为什么我得到一个空集合。我最不确定的是用new Events(response[i]) 设置Month 模型。理想情况下,我会用new Events 初始化events 键,然后将response[i] 添加到它。

任何帮助将不胜感激,

谢谢

【问题讨论】:

  • 抓取时使用promise
  • 这是否意味着在初始化时获取?
  • 我对@9​​87654331@ 部分感到有些困惑。这只是你的代码的一个模型,还是你实际上是在使用这个实现,你在每次迭代时实例化 thisEventthisMonth?我不明白你关于获得一个你没想到的数组的最后一个问题。您的意思是服务器响应(您的 JSON 对象)没有按预期输入,还是您的 for loop 生成了意外的数组。如果您指的是for loop...好吧,您并没有修改任何数组(!)。如果您提供更多详细信息,我可以提供帮助。

标签: json backbone.js collections


【解决方案1】:

我通常这样做:

var promise = calendar.fetch(); 

promise.done(function(response){ 
    //This is where you process the collection that is returned from the server. 
}).fail(function(response){ 
    //In case of failure 
}); 

【讨论】:

  • 非常感谢!我仍然无法创建正确的模型结构。我已经更新了目前的代码。你能看一下// Cycle through events and add to Collection的部分吗?据我所知,这应该可以正常工作,但是如果没有正确的结构,我最终得到的数组比我预期的要长。
【解决方案2】:

我认为您在这里需要做的就是覆盖 Collections 解析函数并执行以下操作:

  parse: function(response) {
    this.status = response.status;
    this.year = response.year;
    return response.events;
  }

parse 函数应始终返回一个数组,从中填充集合。 希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 2013-07-24
    相关资源
    最近更新 更多