【问题标题】:Backbone.js: Load multiple collections with one requestBackbone.js:一次请求加载多个集合
【发布时间】:2012-09-06 20:03:53
【问题描述】:

此时我的代码分别获取每个集合,但考虑到相同的请求是一起发出的,我希望它在一个请求中加载集合。

如果我要合并所有,这就是我的请求响应的样子:

[{id: 5, milestoneName: 'some milestone', tasks: [{id: 1, taskName: 'first task', dueDate: 'Jan 15'}, {id: 2, taskName: 'second task', dueDate: ''}]},{id: 6, milestoneName: 'some other milestone', tasks: [{id: 3, taskName: 'third task', dueDate: 'Jan 16'}, {id: 4, taskName: 'fourth task', dueDate: ''}]}]  

基本上,有包含任务的里程碑。此时,里程碑集合获取里程碑,当它们被获取时,任务集合(每个里程碑的)被初始化并获取任务。这可能需要相当长的时间(2-3 秒,这很明显)。如果我可以在一个请求中加载它们,那么一切都会更快。

milestoneModel = Backbone.Model.extend({});

milestoneCollection = Backbone.Collection.extend({
  url: 'http://some-url',
  model: milestoneModel
});

taskModel = Backbone.Model.extend();

taskCollection = Backbone.Collection.extend({
  url: 'http://task-url',
  model: taskModel
});

我希望 taskCollection 成为每个 milestoneModel 的一部分,并在此请求响应到达后立即重置。

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    啊。嵌套模型并获取所有内容。 :-) 基本上,让您的服务器准确发送您发送的内容。您的嵌套任务集合的 JSON 结构可以正常工作。这就是你要做的。

    在您的里程碑模型中,您修改解析以查找属性tasks,然后相应地处理它。例如:

    parse: function(response) {
        if (_.has(response, 'tasks')) {
            if (this.tasks) {  // Check if this model has a tasks collection already defined
                this.tasks.reset(response.tasks); // It does, so reset it with data
            } else {
                this.tasks = new taskCollection(response.tasks); // It doesn't, so create one
            }
            delete response.tasks;
            // Don't forget to delete tasks from response or it will be passed onto the model
            // set and appear in your attributes
        }
        return response;  // Do pass on all the other attributes that belong to the model
    }
    

    这假定您希望 taskCollection 作为 Milestone 模型的属性而不是属性。它基本上检查任务数组是否作为响应的属性存在,如果有,我们检查模型对象是否已经定义了任务集合。如果是,请使用数据重置集合。如果没有,请使用数据创建集合。

    还有一件事。我不确定你是否必须这样做。但我认为当您fetch() 您的里程碑收藏时,您可能必须传递一个选项parse:true。我有点忘记你什么时候需要这样做,或者这是否是以前 Backbone 的遗物。尝试在您的解析中放置一个 console.log() 以检查您的 Milestone 模型是否正确解析响应。如果不是,请尝试传递parse:true 选项。

    【讨论】:

    • 我已经覆盖了另一个集合的parse 函数,它不需要parse:true。不过我会留意的。谢谢
    • 今天实现了这一点。不需要parse:true :) 完美!
    猜你喜欢
    • 2013-10-15
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 2013-06-03
    • 2012-07-18
    • 2013-07-05
    相关资源
    最近更新 更多