Skip to content

Instantly share code, notes, and snippets.

@sstephenson
Created April 27, 2011 23:33
Show Gist options
  • Save sstephenson/945468 to your computer and use it in GitHub Desktop.
Save sstephenson/945468 to your computer and use it in GitHub Desktop.
# 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