简体   繁体   中英

collection add event firing on view initialisation

I have this code in my backbone application,

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;

    },

I am trying to detect when a model is added to the collection, and then eventually fire a method to render that new record. However I am having problem in that the this.collection.on('add'... ) seems to run when ever the view is initialised and again when a model is saved, how can I only run the method when the model is saved, and not the view being initialised.

I recommend you do this.listenTo(this.collection, ... in your view because when the view is removed it will remove the event and avoid memory leaks.

The add event will get fired on every .set on the collection. If you passed models on collection initialize this will happen ctor -> reset -> add -> set to add those models so you will get reset and add events.

What doesn't make any sense is that your collection should have initialize BEFORE you initialized the view so I don't know why you are getting that event unless you are subsequently adding more models.

To listen to a save event you can use these events on the collection:

request - when the request starts
sync - when the request has happened successfully
error - something went wrong

PS this is a shortcut for this.$el.find -> this.$('.someselector')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM