如何仅在服务器上的集合发生更改时更新主干视图

How to only update a Backbone view if the collection changed on the server?

本文关键字:更新 视图 何仅 服务器 集合      更新时间:2023-09-26

我有一个页面,我轮询通知。如果有任何通知,我用通知填充一个Backbone.js视图。我目前每2秒轮询一次通知,每2秒重新填充一次视图。

function updateNotificationView(ticketId) {
    var ticketNotificationCollection = new TicketNotificationCollection([], {id: ticketId});
    $.when(ticketNotificationCollection.fetch()).done(function() {
        var notificationView = new NotificationsView({collection: ticketNotificationCollection});
        $('#ticket-notifications-area').html(notificationView.render().el);
    });
}
window.notificationsIntervalId = setInterval(function() {updateNotificationView(ticketId);}, 2000);

我现在想要填充视图,如果主干提取集合已经改变,但我不知道我怎么能做到这一点?

谁能给我一个提示,我如何才能填充视图的集合更改?欢迎所有的建议!

[编辑]现在我将函数更改为:

function updateNotificationView(ticketId) {
    var ticketNotificationCollection = new TicketNotificationCollection([], {id: ticketId});
    var notificationsView = new NotificationsView();
    notificationsView.listenTo(ticketNotificationCollection, 'change', notificationsView.render);
    notificationsView.listenTo(ticketNotificationCollection, 'add', notificationsView.render);
    ticketNotificationCollection.fetch();
}

,我将NotificationsView更改为:

var NotificationsView = Backbone.View.extend({
    addNotificationView: function(notification) {
        var singleNotificationView = new SingleNotificationView({model: notification});
        this.$el.append(singleNotificationView.render().el);
    },
    render: function() {
        console.log('ITS BEING CALLED!!');
        this.collection.each(this.addNotificationView, this);
        $('#ticket-notifications-area').html(this);
    }
});

我现在得到"ITS正在被调用!!"在控制台中每两秒钟,但也是一个错误:"未捕获的TypeError: Cannot read property 'each' of undefined."。我知道为什么会出现这个错误;这是因为集合从来没有实际插入到视图中。然而,我不明白我该如何解决这个问题。还有什么建议吗?

我假设您正在收集模型以响应您的请求作为JSON。

方法1:

您可以简单地将集合设置为JSON。并将集合绑定到change事件。如果集合发生任何变化,将触发回调函数。在回调函数中,你可以渲染你的视图。

注意:change事件只有在它所包含的模型发生任何变化时才会被触发。

someCollection.on('change', function(){
    someView.render()
  });
方法2:

你可以使用Backbone的listenTo方法,来呈现更改集合时的视图。

someView.listenTo(someCollection, 'change', someView.render);