Created
December 26, 2012 23:44
-
-
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
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
//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]); | |
}) | |
}); | |
} | |
}); | |
})(_) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
where _.mapObject is
_.mixin({
})