简体   繁体   中英

Backbone Collection Not firing Add Event

So i have a problem whereby I have a backbone collection that am using to create function to save data to a REST API. The data is saved to the server and a model is added to the current collection but then the add event for the collection is not fired.Below are snippets of the code The views initialize function

intialize : function() {
        this.listenTo(this.collection, 'add', this.updateList);
    },      

The updateList function only does a console log.The views function that saves data using the collection is:

cards = this.collection;
        debugger
        cards.create(data, {
            success : function(model, response) {
                console.log("success on saving card");
                console.log(response);
                console.log("Updating list");
                console.log(cards);
            },
            error : function(model, response) {
                console.log("error on saving card");
                console.log(model);
                console.log("response");
                console.log(response);
            }
        })
        return false;

Try this code in your view:

initialize: function() {
    this.collection.on('add', this.updateList, this);
}

Or:

var someCollection = new SomeCollection();
var view = new SomeView({collection: someCollection});
view.listenTo(someCollection, 'add', view.updateList);

why don't you just use: this.model.on('change', doAction, this); inside the view? if I understood correctly, this is a better solution since your model is changing. plus, I couldn't find anywhere a place where the ListenTo() is mandatory over the On() function, can you tell me where you saw it?

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