没有调用Backbonejs视图来更新(添加)集合

时间:2013-11-14 06:51:59

标签: jquery backbone.js underscore.js

我的视图,(标题,视图)的默认集合除了我将集合添加到现有默认值之外。

当新集合添加到集合列表时,我无法获得有关更新的控制台信息。

这是我的代码:

var data = [
    {name:"name1", age:"01"},
    {name:"name2", age:"02"},
    {name:"name3", age:"03"},
    {name:"name4", age:"04"},
    {name:"name5", age:"05"}
];


var model = Backbone.Model.extend({
    defaults:{
        name : "yet to be describe",
        age : "no age data"
    }
});

var collection = Backbone.Collection.extend({
    model : model
});

var view = Backbone.View.extend({
    initialize : function () {
        console.log ("view initiated");
    }
});

var views = Backbone.View.extend({
    initialize : function () {
        _.bindAll(this, 'render');
    },
    render : function () {
         console.log ( this.collection.length ); // i am not getting updates
    }
})

var headerView = Backbone.View.extend({
    initialize : function () {
         _.bindAll(this, 'render');
    },
    render : function () {
        console.log ( this.collection.length ); // i am not getting updates
    }
})

var coll = new collection(data);
var myApp = new views({collection : coll}); // not called on update
var header = new headerView({collection : coll}); // not called on update

$("button").on("click", function () {
    coll.add({name:("name"+(coll.size()+1)), age : coll.size()+1 });
})

请你帮我解决一下我的问题..?

Live Demo

2 个答案:

答案 0 :(得分:1)

对于您的视图,我想您希望在添加模型时监视集合的渲染,因此您需要绑定到集合事件:

var views = Backbone.View.extend({
  initialize : function () {
    this.collection.bind('add', this.render, this); //Binding render to the collections add event
  },
  render : function () {
     console.log ( this.collection.length );
  }
})

答案 1 :(得分:0)

在您的收藏中绑定事件:

var collection = Backbone.Collection.extend({
    model : model,
    initialize : function(){
        this.on('add', function(){
           /// DO what needs to be done on adding model to collection
            myApp.render(); 
           header.render();
        })
    }
});