js999
js999

Reputation: 2083

Comparator in backbone requires the sort call when adding a new model?

I defined the Comparator in my Backbone.Collection.

When I add a model to the that collection should I call the sort method?

this.collection.add(this.newModel);
this.collection.sort(); // should I add this line?

According the documentation not, but my app seems to need it. any idea?


I added jsfiddle..but I have another problem...any idea how to fix it?

Upvotes: 1

Views: 626

Answers (2)

fguillen
fguillen

Reputation: 38812

It shouldn't be needed to call sort(), the comparator() method is used in every Collection insert.

Check the working example in jsFiddle

Your problem should be somewhere else.

Upvotes: 1

The Internet
The Internet

Reputation: 8103

No, use the negative sign when you return an object from your comparator function. This is another way to sort elements.

  //Model
     comparator: function(activity){

                var date = new Date(activity.get('created_at'));
                return -date.getTime();

            }

//View
 events : {
        'click .refresh' : 'refresh',
        'click .reverse' : 'reverse'
    },

    refresh : function() {

     this.collection.fetch();
    console.log('refresh', this.collection);
     this.render();

    },

    reverse : function() {

        var $ref = $(".notifyRefresh");

        console.log("you clicked reverse");

        console.log(this.collection, "collection");

        this.collection.sort();
    }

Upvotes: 1

Related Questions