Last active
August 29, 2015 14:00
-
-
Save bahattincinic/11248118 to your computer and use it in GitHub Desktop.
Underscore adaptation of '_.where' for knockout
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
_.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; | |
} | |
}); |
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
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