Skip to content

Instantly share code, notes, and snippets.

@bahattincinic
Last active August 29, 2015 14:00
Show Gist options
  • Save bahattincinic/11248118 to your computer and use it in GitHub Desktop.
Save bahattincinic/11248118 to your computer and use it in GitHub Desktop.
Underscore adaptation of '_.where' for knockout
_.mixin({
koMatches: function (attrs) {
return function (obj) {
if (obj == null){
return _.isEmpty(attrs);
}
if (obj === attrs){
return true;
}
for (var key in attrs) {
if (typeof(obj[key]) == 'function') {
if (attrs[key] !== obj[key].call()) {
return false;
}
} else {
if (attrs[key] !== obj[key]) {
return false;
}
}
}
return true;
}
},
koWhere: function (obj, attrs) {
var results = [];
var predicate = _.koMatches(attrs);
if (obj == null){
return results;
}
_.each(obj, function (value, index, list) {
if (predicate.call(attrs, value)){
results.push(value);
}
});
return results;
}
});
function Test(){
this.attr = ko.observableArray()
}
var hede = new Test();
ko.applyBindings(hede);
hede.attr.push({"key": ko.observable(1)});
hede.attr.push({"key": ko.observable(2)});
console.log(_.koWhere(hede.attr(), {"key":2}));
[>object]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment