To Top

Our Blog

Guru Technologies

Better jquery each loop for coffeescript

When writing object-oriented code in coffeescript, I’ve found that the jquery each method is insufficient, due to its use of “this”.  I am forced to use the following syntax:

$('.thing').each (index, thing) =>
    width: @width()

I’ve created an alternative which works better for this use case.  It passes the object as both “this” and as the first argument, and wraps them both in a jquery object automatically:

$('.thing').loop (thing) =>
    width: @width()

In cases where you don’t want access to the original “this”, it is also useful.  Here is an example with “each”:

$('.photo').each ->

With “loop”, there’s no need to wrap “this” with a jquery object:

$('.photo').loop ->

Here is the source code for $.loop:

# Better each() for use with coffeescript
# 1. Wraps child in jquery object
# 2. Sets child first argument, so that fat-binding can be used.
# 3. Sets @ as well, for normal binds
jQuery.fn.loop = (block) ->
  for i in @
    element = jQuery(i)
    res = element, element
    break if res == false

1 Comment

  1. Tonatiuh Núñez June 3, 2013 at 5:04 pm -

    Short but useful, thanks for the advice.