2013-09-23 81 views
0

我有我的模型骨幹集合視圖中添加不被稱爲與模型

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); 

當colonyview呈現addOne第一次得到一個客戶端作爲參數,因爲它通過所謂的addAll。但是當addOne通過add事件我在檢查item看到所謂的下一次是不是一個client

環R {CID: 「C606」,屬性:對象,集合:R,_changing:假的,_previousAttributes:對象...}

+0

r {cid:「c606」,attributes:Object,collection:r,_changing:false,_previousAttributes:Object ...}是一個從backbone.model擴展的模型對象。它可以是客戶端模型的一個實例。也許你可以登錄item.toJSON()來查看屬性 – nilgun

+1

我認爲你必須編寫colony.fetch({update:true,remove:false})。如果沒有刪除,每個新模型都不會觸發「添加」事件。 http://backbonejs.org/#Collection-fetch – redconservatory

+0

@nilgundag我在addOne中檢查了item.toJSON()它是'Object {clients:Array [1]}'這是一個殖民地(collection) –

回答

0

我想我想通了你的問題。

這裏是一個工作撥弄你的代碼: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' 
}] 

既然你說你正在對象{客戶:數組[1]},可能是你的服務器返回:

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

這裏是小提琴這表明你的情況:http://jsfiddle.net/nilgundag/TxZxp/

您應該將服務器代碼更改爲僅發送客戶端數組,而不是包含屬性客戶端和關聯數組的對象。

+0

謝謝。這就是我早上看到的。我重寫了'parse'方法並返回'clients' –

+0

現在問題是'collection.fetch {update:true}'沒有正確合併。我使用'ip'字段作爲'idAttribute'是我的'客戶端'模型,但它仍然'添加'所有內容而不是合併 –

+0

var Client = Backbone.Model.extend({id}屬性:「ip」 });在小提琴中工作:http://jsfiddle.net/nilgundag/KbwHZ/ – nilgun