Joseph.Bosire
Joseph.Bosire

Reputation: 31

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;

Upvotes: 2

Views: 1341

Answers (2)

joni jones
joni jones

Reputation: 2995

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);

Upvotes: 1

Labib Ismaiel
Labib Ismaiel

Reputation: 1340

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?

Upvotes: 0

Related Questions