Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Extend jQuery objects with Underscore collection methods.
#
# Each collection method comes in two flavors: one prefixed
# with _, which yields a bare DOM element, and one prefixed
# with $, which yields a jQuery-wrapped element.
#
# So if `this` is a jQuery object, instead of:
#
# _.max @, (el) -> $(el).height()
#
# you can write:
#
# @$max (el) -> el.height()
#
# or:
#
# _.max @$invoke 'height'
#
# An improvement? Probably not. Just a quick response to:
# https://twitter.com/#!/dhh/status/63371606969430016
# https://twitter.com/#!/dhh/status/63371795335610368
iteratorNames = [
'each', 'map', 'reduce', 'reduceRight', 'detect', 'select',
'reject', 'all', 'any', 'max', 'min', 'sortBy'
]
for iteratorName in iteratorNames then do (iteratorName) ->
$.fn["_#{iteratorName}"] = ->
_[iteratorName] @, arguments...
$.fn["$#{iteratorName}"] = (iterator, args...) ->
iteratorWith$ = if iterator? then (element, args...) ->
iterator $(element), args...
_[iteratorName] @, iteratorWith$, args...
methodNames = [
'pluck', 'invoke'
]
for methodName in methodNames then do (methodName) ->
$.fn["_#{methodName}"] = ->
_[methodName] @, arguments...
$.fn["$#{methodName}"] = ->
_[methodName] (_.map @, (element) -> $ element), arguments...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment