Search code examples
javascriptbackbone.jsunderscore.js

Backbone Where function on an attribute which is an object


I have a backbone model like so:

    Name: Test1
 size: {Key: "M" Value: "Med"}

Now I am trying to get a total for the key M. the function below is not working:

getTotals: function(property) {
        return this.where({ size: { Key: property }}).length;
    }

I call it like so:

collection.getTotals("M")

Is there a way to do this with the backbone where function?


Solution

  • I don't believe there is a way to do this with backbone's where method. Have a look at the documentation (http://backbonejs.org/#Collection-where) and consider what it says: "useful for simple cases of filter" (emphasis added).

    Yours is not a simple case because the value of size is an object, but we still use filter:

    collection.filter(function(model) {
        return model.get('size').Key == 'M'
    });