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) =>
  $(thing).css
    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) =>
  thing.css
    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 ->
  $(@).hide()

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

$('.photo').loop ->
  @hide()

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 = block.call element, element
    break if res == false

1 Comment

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

    Short but useful, thanks for the advice.

Leave a Comment

Your email address will not be published. Required fields are marked *