Last active
August 29, 2015 13:57
-
-
Save m-vdb/9367150 to your computer and use it in GitHub Desktop.
Undescore mixins : whereDeep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// inspired from _.matches | |
function deepMatch (attrs) { | |
return function (obj) { | |
var attrVal, objVal; | |
if (obj === attrs) return true; //avoid comparing an object to itself. | |
for (var key in attrs) { | |
attrVal = attrs[key]; | |
objVal = obj[key]; | |
if (_.isObject(attrVal) && _.isObject(objVal)) { | |
if (!deepMatch(attrVal)(objVal)) { | |
return false; | |
} | |
} | |
else if (attrVal !== objVal) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
} | |
_.extend(Backbone.Collection.prototype, { | |
// inspired from Collection.where | |
whereDeep: function(attrs) { | |
if (_.isEmpty(attrs)) { | |
return []; | |
} | |
return this.filter(function(model) { | |
return deepMatch(attrs)(model.attributes); | |
}); | |
} | |
}); | |
_.mixin({ | |
// inspired from _.where | |
whereDeep: function(obj, attrs) { | |
return _.filter(obj, deepMatch(attrs)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment