0

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

当一个新集合添加到集合列表时,我没有得到有关更新的控制台信息。

这是我的代码:

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

你能帮我弄清楚我的问题吗..?

现场演示

4

2 回答 2

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 );
  }
})
于 2013-11-14T07:17:05.077 回答
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();
        })
    }
});
于 2013-11-14T07:18:31.463 回答