2
votes

Mates I'm trying to get the greater attribute from a backbone collection amongst all its contained models.

As an example:

App.Models.Example = Backbone.Model.extend({    
    defaults: {
        total: 0,
        created_at: '0000-00-00',
        updated_at: '0000-00-00'
    }

});

App.Collections.Examples = Backbone.Collection.extend({
    model: App.Models.Example,
    url: 'examples'
});

var examples = new App.Collections.Examples();
examples.sync();

What I need to get, is the greater created_at field.

How could I do that?

Thanks!

1

1 Answers

0
votes

I think you are asking to retrieve the model from the collection that has the most recent created_at date in the collection yes?

If so, you use the underscore max function, like this:

var mostRecentDateModel = examples.max(function(model){ 
    return model.get("created_at"); 
});

// this prints the most recent date that you are after
console.log(mostRecentDateModel.get("created_at"));

You'll need to keep in mind that if the created_at attribute of your model is not a JavaScript date (it might be a string), the max function may not return what you expect. So it may be worth ensuring it really is a Date and/or converting it to one.

Hope this helps