Dan Walmsley
Dan Walmsley

Reputation: 2821

Backbone collection only fires parse or reset, I think I need both

Here is my problem

I have a very simple backbone collection getting some data for me. Everything works fine like this:

DealershipContacts.Collection = Backbone.Collection.extend({
    url:jarvisUrl ("dealership_contacts"),
    parse:function(response) {
        console.log('parse called');
        return response.data;

    },
    initialize : function(){
        _.bindAll(this, 'reset', 'parse');
    }
});

When fetch is called parse logs to the console as expected.

But after that point I would like to listen for the reset event so I can use the collection to populate the source data of a bootstrap typeahead input. So I did this:

DealershipContacts.Collection = Backbone.Collection.extend({
    url:jarvisUrl ("dealership_contacts"),
    parse:function(response) {
        console.log('parse called');
        console.log(response);
        return response.data;

    },
    reset:function(){
        console.log("change fired");
        $('.dealership_typeahead').typeahead({source:this.pluck('user_name')});
        return true;
    },
    initialize : function(){
        _.bindAll(this, 'reset', 'parse');
    }
});

And now the parse event is never fired and the collection does not populate I can't figure out why.

Any insights much appreciated, thanks.

Upvotes: 2

Views: 799

Answers (1)

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

You are not hooking up to the reset event with that code. You are overriding the default Backbone.Collection reset method (you don't want to do that).

DealershipContacts.Collection = Backbone.Collection.extend({
    url:jarvisUrl ("dealership_contacts"),

    initialize: function(models, options){
        this.on('reset', this.doStuff, this);
    },
    parse:function(response) {
        // you DO want to override the default parse method
        return response.data;
    },
    // don't call this method `reset` :)
    doStuff:function(){
        // do something now that collection is fetched
    }
});

I think you were confusing _.bindAll with listening for Backbone events. bindAll does something different, and you don't need it for this.

Upvotes: 5

Related Questions