集合添加事件在视图初始化时触发

collection add event firing on view initialisation

本文关键字:初始化 视图 添加 事件 集合      更新时间:2023-09-26

我的主干应用程序中有这段代码,

createNewProject: function(e) {
    e.preventDefault();
    this.createNewProject = new app.CreateNewProject({ 
        collection: this.dropdownListProjectCollection
    });
}
app.CreateNewProject = Backbone.View.extend({
    el: '.modal',
    template: _.template( $("#tpl-create-new-project").html() ),
    events: {
        'click input[type="submit"]' : 'saveBasicProject'
    },
    initialize: function() {
        this.collection.on("add", console.log("added"));
        this.$el.find("h4").text("Create new project");
        this.$el.find(".modal-body").html( this.template() );
        this.render();
        return this;
    },

我试图检测何时将模型添加到集合中,然后最终触发一个方法来呈现该新记录。但是,我遇到的问题是,this.collection.on('add'...)似乎在视图初始化时运行,当保存模型时再次运行,我如何才能仅在保存模型时运行该方法,而不是初始化视图。

我建议您在视图中执行this.listenTo(this.collection, ...,因为当视图被删除时,它将删除事件并避免内存泄漏。

add事件将在集合上的每个.set上触发。如果您在集合初始化上传递模型,这将发生ctor -> reset -> add -> set以添加这些模型,因此您将获得resetadd事件。

没有任何意义的是,你的集合应该在你初始化视图之前初始化,所以我不知道为什么你得到那个事件,除非你随后添加更多的模型。

要监听保存事件,您可以在集合上使用这些事件:

request -当请求开始时
sync -当请求成功发生时
error -出错

PS这是this.$el.find -> this.$('.someselector')的快捷方式