集合在Backbone中添加事件监听器

时间:2013-06-07 20:40:55

标签: javascript jquery backbone.js backbone-events backbone-collections

每当我向我的收藏中添加新模型时,我都会尝试更新我的视图。我的第一个问题是当我保存该模型时,我会自动将模型添加到我的集合中,例如:

PostsApp.Views.Form = Backbone.View.extend({
    template: _.template($('#form-template').html()),
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
    },
    events:{
        'click button' : 'save'
    },

    save: function(e){
        console.log("is this working");
        e.preventDefault();
        var newname = this.$('input[name=name-input]').val();
        var newadress = this.$('input[name=adress-input]').val();
        this.model.save({name: newname, adress : newadress});
    }


});

还是我还要做collection.add()

除了在我的视图中看到新模型之外,我正在尝试添加这样的'add'事件监听器:

PostsApp.Views.Posts = Backbone.View.extend({
    initialize: function(){
        this.collection.on('add', this.addOne, this);

    },
    render: function(){
        this.collection.forEach(this.addOne, this);
    },

    addOne: function(post){
        var postView = new PostsApp.Views.Post({model:post});
        postView.render();
        this.$el.append(postView.el);
    }
});

这不仅不起作用,而且当我添加初始化方法时,它只是在首次加载页面时复制模型中的所有内容。

1 个答案:

答案 0 :(得分:13)

Nope ..当你执行model.save时,它只会创建一个僵尸模型(如果它还不是集合的一部分.ie如果保存了新模型)不属于任何收藏品。

因此,系统不会触发添加事件。

如果您希望触发添加事件,请使用create集合方法,然后将知道必须添加新模型的集合。

collection.create({model});

然后它会在内部将模型添加到集合中并触发add event

最好使用listenTo而不是使用on附加事件

this.listenTo(this.collection, 'add', this.addOne);

<强>代码

PostsApp.Views.Form = Backbone.View.extend({
    template: _.template($('#form-template').html()),
    render: function () {
        this.$el.html(this.template(this.model.toJSON()));
    },
    events: {
        'click button': 'save'
    },

    save: function (e) {
        console.log("is this working");
        e.preventDefault();
        var newname = this.$('input[name=name-input]').val();
        var newadress = this.$('input[name=adress-input]').val();
        this.collection.create({
            name: newname,
            adress: newadress
        });
    }
});

PostsApp.Views.Posts = Backbone.View.extend({
    initialize: function () {
        this.listenTo(this.collection, 'add', this.addOne);

    },
    render: function () {
        this.collection.forEach(this.addOne, this);
    },

    addOne: function (post) {
        var postView = new PostsApp.Views.Post({
            model: post,
            collection : this.collection
        });
        postView.render();
        this.$el.append(postView.el);
    }
});
相关问题