主干集合视图添加未使用模型调用

Backbone collection View add not being called with a model

本文关键字:未使用 模型 调用 添加 视图 集合      更新时间:2023-09-26

我有我的模型

var Client = Backbone.Model.extend({});
var Colony = Backbone.Collection.extend({
    url: '/presence/knock',
    model: Client
});

视图

var ClientView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    template: _.template('...'),
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});
var ColonyView = Backbone.View.extend({
    initialize: function(){
        _.bindAll(this, 'addOne', 'addAll');
        this.collection.bind('add', this.addOne);
        this.collection.bind('refresh', this.addAll);
        this.collection.bind('change', this.addAll);
    },
    addOne: function(item){
        console.log('addOne', item);
        var view = new ClientView({
            model: item
        });
        $(this.el).append(view.render().el);
    },
    addAll: function(){
        var self = this;
        this.collection.each(function(item){
            self.addOne(item);
        });
    },
    render: function(){
        this.addAll();
        return this;
    }
});

我用/presence/knock上的彗星更新了收藏.

var colony = new Colony([{
    ip: '127.0.0.1',
    name: 'localhost.localdomain',
    lsup: 'now'
}]);
setInterval(function(){
    colony.fetch({
        update: true
    });
}, 5*1000);
var colonyView = new ColonyView({
    collection: colony
});
$("#clients-board").append(colonyView.render().el);

第一次渲染殖民地视图时,addOne获取客户端作为参数,因为它通过 addAll 调用。 但是下次通过我在检查器中看到的事件调用add addOneitem不是client

r

{cid: "c606", attributes: Object, collection: r, _changing: false, _previousAttributes: Object...}

我想

出了你的问题。

这是您的代码的工作小提琴:http://jsfiddle.net/nilgundag/KbwHZ/

我使用 mockjax 来模拟服务器,它返回的内容如下:

[{
    ip: '127.0.0.1',
    name: 'localhost.localdomain',
    lsup: 'now'
},
{
    ip: '127.0.0.2',
    name: 'localhost.localdomain',
    lsup: 'now'
}]

既然你说你正在获取对象 {client: Array[1]},你的服务器可能返回:

[{
        clients:[{
                ip: '127.0.0.1',
                name: 'localhost.localdomain',
                lsup: 'now'
        }]
}]

这是小提琴,它展示了您的情况:http://jsfiddle.net/nilgundag/TxZxp/

应将服务器代码更改为仅发送客户端数组,而不发送包含属性客户端和关联数组的对象。