1

I'd like to get some models in my collection that have the attribute unit. My current method involves this,

        var unitIds = ciLocal.where({unit: !null});
        console.log(unitIds.length);

The weird thing is that removing ! returns 58 (the total minus those that unit is not null) values while the code above returns 0.

Can anyone suggest a good way to loop my collection and return those models that have anything in unit?

Its probably worth mentioning that unit contains two values, one being unitID and the other being an array of more values. I need to get the whole model back and not just the unit section.

In this screenshot you can see that 68 has null while 69 has object. enter image description here

{"carID":"37","unit":{"unitID":"37_Chaffinch_75","positionHistory":[{"lat":"51.474312","long":"-0.491672","time":"2011-07-08 11:24:47","status":"1","estimatedSpeed":"0","lastSoundFileName":"Car park Exit","lastSoundRange":"10","lastSoundTime":"2011-07-08 11:25:03","isToday":false,"minutesAgo":1028188}]},"registration":"CJ-361-YG","color":"Luxor","phone":"","model":"SDV8"}

4

1 回答 1

3

您可以在集合上使用_.filter来指定自定义验证函数。

filter _.filter(list, iterator, [context])
查看列表中的每个值,返回一个包含所有通过真值测试(迭代器)的值的数组。

像这样的东西应该使模型具有定义的非空值

var c = new Backbone.Collection([
    {id: 1, unit: 1},
    {id: 2, unit: null},
    {id: 3}
]);

c.filter(function(model) {
    var v = model.get('unit');
    return ((typeof(v)!=='undefined') && (v!==null));
})

还有一个演示http://jsfiddle.net/nikoshr/84L2R/

于 2013-06-21T10:53:29.193 回答