【问题标题】:Nested collections with Backbone.Marionette使用 Backbone.Marionette 嵌套集合
【发布时间】:2012-08-28 15:57:37
【问题描述】:

我想创建一个日历,它是一天的集合,每一天都是约会的集合。 day对象的结构是:

day:{
    date:'08-06-2012',
    appointment: {
        time_begin:'12:55',
        time_end: '16:40',
        customer: 'Jaime'
    }
}

此时我有这个模型和视图:

// CALENDAR COLLECTION
App.Calendar.Collection = Backbone.Collection.extend({
    // MODEL
    model: App.Day.Model
}

当日历集合从服务器获取数据时,它会获取包括约会在内的完整日期对象。

// CALENDAR VIEW
App.Calendar.View = Backbone.Marionette.CompositeView.extend({
    // TEMPLATE
    template: Handlebars.compile(templates.find('#calendar-template').html()),
    // ITEM VIEW
    itemView: App.Day.View,
    // ITEM VIEW CONTAINER
    itemViewContainer: '#calendar-collection-block'
});

// DAY MODEL
App.Day.Model = Backbone.Collection.extend({
    // PARSE
    parse:function(data){
        console.log(data);
        return data;
    }
});

// DAY VIEW
App.Day.View = Backbone.Marionette.CompositeView.extend({
    collection: App.Day.Model,
    itemView: App.CalendarAppointment.View, //---->I NEED TO DEFINE THIS, NOT SURE HOW
    template: Handlebars.compile(templates.find('#day-template').html())
});

day 模型需要是约会的集合,并且不需要从服务器获取数据,因为它每天都在里面。

我该怎么做?

【问题讨论】:

    标签: backbone.js marionette


    【解决方案1】:

    如果我对问题的理解正确,您是在问如何从Day 模型、Appointment 集合中获取数据到CalendarApointmentView itemView?

    您的Day.View 可以设置为填充此复合视图的collection,然后将其推送到项目视图中:

    
    // DAY VIEW
    App.Day.View = Backbone.Marionette.CompositeView.extend({
        collection: App.Day.Model,
        itemView: App.CalendarAppointment.View,
        template: Handlebars.compile(templates.find('#day-template').html()),
    
        initialize: function(){
    
          // since `this.model` is a `Day` model, it has the data you need
          this.collection = this.model.get("CalendarAppointments");
    
        }
    });
    

    需要注意的一点:this.collection 必须是有效的 Backbone.Collection。如果您的模型将约会数据存储为一个简单的数组,那么您需要这样做:

    
    var appointments = this.model.get("CalendarAppointments");
    this.collection = new AppointmentCollection(appointments);
    

    希望对您有所帮助。

    【讨论】:

    • @Derick,对于深度嵌套的集合,compositeView.itemView 可以指向另一个 CompositeView 吗?可以嵌套多深有限制吗?
    【解决方案2】:

    这看起来像是 backbone-relational 的完美用例,它会自动处理您的嵌套数据解析并创建嵌套集合结构。

    【讨论】:

    • 问题更多的是围绕如何构建视图?
    猜你喜欢
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 2020-11-26
    • 2020-12-12
    • 2014-10-31
    相关资源
    最近更新 更多