簡體   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