Using Backbone.js & Underscore, how to get a count

2019-04-01 05:44发布

I have a notifications model for notifications

// MODEL
NotificationModel = App.BB.Model.extend({
    defaults : {}
});


// COLLECTION
NotificationCollection = App.BB.Collection.extend({
    model: NotificationModel,
    url: '/notifications',

    initialize : function() {
        var me = this;
        me.fetch();
    }

});

The collection is fetching from the server correctly and has the following fields (id, read) where read is true or false.

How can I get the total number count of items that are read == false? ... Unread item count?

Thanks

3条回答
啃猪蹄的小仙女
2楼-- · 2019-04-01 06:14

A structured solution would be to create these methods in your collection:

read: function() {
    return this.filter(function(n) { return n.get('read'); });
},

unread: function() {
    return this.filter(function(n) { return !(n.get('read')); });
}

If you need the count, you can just add .length to the end of the method.

查看更多
迷人小祖宗
3楼-- · 2019-04-01 06:29

Using the underscore's filter method and general JavaScript .length schould do it.

Backbone's documentation has an example of filter, you just need to return read equals false.

var unread = Notes.filter(function(note) {
    return note.get("read") === false; 
}).length;

submitting from my mobile phone, sorry for the brief answer

查看更多
你好瞎i
4楼-- · 2019-04-01 06:33

Backbone Collection's where method might be of use.

var read = this.where({ read: true });
var unread = this.where({ read: false });

This doesn't work if read isn't true or false -- in that case, you should use filter as the other answers suggest.

查看更多
登录 后发表回答