Using Backbone.js & Underscore, how to get a count of items from the model?

我只是一个虾纸丫 提交于 2019-12-21 05:36:13

问题


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


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/8529791/using-backbone-js-underscore-how-to-get-a-count-of-items-from-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!