繁体   English   中英

骨架.js集合的用法

[英]backbone.js collection usage

我在维护我的收藏时遇到了问题。 首先,我通过提取将与会者加载到集合中。 这会将现有与会者从数据库加载到集合中。 我还有一个按钮,允许用户添加新的与会者。 手动输入与会者时,似乎会通过提取清除加载到集合中的模型并重新开始。 现在,所有手动添加的与会者都将填充集合; 但是,我希望加载并手动添加与会者来填充此列表。

var InviteeView = Backbone.View.extend({
tagName: "tr",
initialize: function() {
    this.collection = new InviteeJSONList();    
    _.bindAll(this, 'render','appendItem','remove','saveInvitee');
},
events: {
    "click .removeInvitee":"remove",
    "click .saveInvitee":"saveInvitee"
},
render: function() {
    var source = $("#invitee-template").html();
    var template = Handlebars.compile(source);
    var context = inviteeListJSON.attributes['json'];
    var html=template(context);

    $(this.el).html(html);

    return this;
},
appendItem: function() {
    $("#attendees").append(this.render().el);
},
remove: function() {
    $(this.el).remove();
},
saveInvitee: function() {
    var value = $(this.el).find('select').val();
    var model = this.collection.attributes['json']['invitees'];
    model = model.filter(function(attributes) {return attributes.encrypted_id==value});
    var attendee = new Attendee({
        user_id: model[0]['id'],
        meeting_id: '<?=$mid?>',
        status: 'Uncomfirmed',
        first_name: model[0]['first_name'],
        last_name: model[0]['last_name'],
        email: model[0]['email'],
        user_uuid: model[0]['encrypted_id'],
        unavailable_dates: model[0]['unavailable_dates']
    });

    attendeeView.addAttendeeItem(attendee.attributes)
    this.remove();
}
});

var AttendeeList = Backbone.Collection.extend({
model: Attendee,
url: '<?=$baseURL?>api/index.php/attendees/<?=$mid?>&timestamp=<?=$timestamp?>&userid=<?=$userid?>&apikey=<?=$apikey?>',
parse: function(response) {
    if(response!="No History") {
        $.each(response['attendees'], function(key, value) {
            attendeeView.addAttendeeItem(value);
        });
        $('.loading_attendees').hide();
    }
    else {
        $('.loading_attendees').html("No attendees exists for this meeting.");
    }
}
});

var AttendeeView = Backbone.View.extend({
el: $('body'),
initialize: function() {
    _.bindAll(this, 'render','fetchAttendees', 'appendItem', 'addAttendeeItem');
    this.counter=0;
    this.collection = new AttendeeList();
    this.collection.bind('add', this.appendItem);
    this.fetchAttendees();
},
events: {
    "click #addInvitee":"appendInvitees",
},
appendInvitees: function() {
    var inviteeView = new InviteeView();
    inviteeView.appendItem();
},
render: function() {

},
fetchAttendees: function() {
    this.collection.fetch({
        success: function(model, response) {

        },
        error: function(model, response) {
            $('#loading_attendees').html("An error has occurred.");
        }
    });
},
appendItem: function(item) {
    var attendeeItemView = new AttendeeItemView({
        model: item
    });
    $("#attendees").append(attendeeItemView.render().el);
    attendeeItemView.updateAttendeeStatusSelect();

},
addAttendeeItem: function(data) {
    this.counter++;
    var attendee = new Attendee({
        id: data['id'],
        user_id: data['user_id'],
        meeting_id: data['id'],
        status: data['status'],
        comments: data['comments'],
        attended: data['datetime'],
        first_name: data['first_name'],
        last_name: data['last_name'],
        email: data['email'],
        counter: this.counter,
        user_uuid: data['user_uuid'],
        unavailable_dates: data['unavailable_dates']
    });

    this.collection.add(attendee);
},
});

通过fetch()加载集合(从REST API加载的2个项目)后:

console.log(this.collection.models) outputs:
[d]
[d,d] 

然后,当我通过按钮手动添加与会者时,收藏集似乎已重置:

console.log(this.collection.models) outputs:
[d] 

很好,因为它有很多路要走。 我可能会以不同的方式构造它,以利用实例化模式的Backbone方法,但是工作代码才是真正的目标,因此,这些只是我的想法:

  • 与其实际在Collection parse()方法中实例化模型,不如让parse返回一个数据对象数组,Backbone将从该数据对象实例化模型,并触发一个

  • 而不是在AttendeeView内部但在View类外部为Collection调用fetch

  • 让AttendeeView代表单个与会者的视图,或者将其命名为AttendeeListView并呈现列表

例如:

AttendeeList = Backbone.Collection.extend({
 ...
   parse: function(response) {
           // create an array of objects from which the models can be parsed
           var rawItems = [];
               $.each(response['attendees'], function(key, value) {
                 rawItems.push({
                        id: data['id'],
                        user_id: data['user_id'],
                        meeting_id: data['id'],
                        status: data['status'],
                        comments: data['comments'],
                        attended: data['datetime'],
                        first_name: data['first_name'],
                        last_name: data['last_name'],
                        email: data['email'],
                        counter: this.counter,
                        user_uuid: data['user_uuid'],
                        unavailable_dates: data['unavailable_dates']
                    });
                });
              return rawItems;
           },
         ...
       }

然后使用成功/失败回调:

  AttendeeList.fetch( onListFetchSuccess , onListFetchFail );

或侦听触发的reset事件:

  AttendeeList.on('reset', createAttendeeListView );

(我实际上并没有编辑和运行代码,这只是一个概述)

我最终通过从集合中删除url参数和解析函数并进入视图来解决了该问题。 现在一切都按预期进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM