Skip to content

Instantly share code, notes, and snippets.

@togakangaroo
Created December 26, 2012 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save togakangaroo/4384094 to your computer and use it in GitHub Desktop.
Save togakangaroo/4384094 to your computer and use it in GitHub Desktop.
Make a limited set of underscore functions transparently unwrap knockout observables while not affecting non-observables
//make a limited set of underscore functions transparently unwrap knockout observables
(function knockoutifyUnderscore(_) {
var unwrap = ko.utils.unwrapObservable;
//These can be shimed in a standard way
var koFriendly = ['map', 'filter', 'find', 'each', 'findBy', 'first', 'last', 'head', 'tail', 'union', 'compact', 'flatten', 'difference', 'without'];
var oldMap = _.map;
for (var _i = 0; _i < koFriendly.length; _i++) {
(function(fnName) {
var originalFn = _[fnName];
_[fnName] = function() {
var args;
args = oldMap(arguments, unwrap);
return originalFn.apply(_, args);
};
})(koFriendly[_i]);
}
//These underscore commands need special attention
_.mixin({
where: function(collection, query) {
query = _.mapObject(query, function(val, key){
return [key, unwrap(val)]
});
return _.filter(collection, function(item){
return _.all(query, function(queryVal, key) {
return queryVal === unwrap(item[key]);
})
});
}
});
})(_)
@togakangaroo
Copy link
Author

where _.mapObject is
_.mixin({

    // Create object from a callback that returns [name, value] pairs. We use this combination a lot
    // so might as well bake it into the framework
     mapObject: _.compose(_.object, _.map)

})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment