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

Gor*_*ven 5 javascript jquery backbone.js backbone-events backbone.js-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});
    }


});
Run Code Online (Sandbox Code Playgroud)

还是我还要做collection.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);
    }
});
Run Code Online (Sandbox Code Playgroud)

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

Sus*_* -- 13

没有 ..当你这样做时model.save,它只会创建一个僵尸模型(如果它还不是集合的一部分.ie如果保存了新模型),这不是任何集合的一部分.

因此,不会为集合触发您的添加事件.

如果要触发add事件,请使用createcollection方法,然后将知道必须添加新模型的集合.

collection.create({model});
Run Code Online (Sandbox Code Playgroud)

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

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

this.listenTo(this.collection, 'add', this.addOne);
Run Code Online (Sandbox Code Playgroud)

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);
    }
});
Run Code Online (Sandbox Code Playgroud)