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

Warning: Declaration of guru_walker_comment::start_el(&$output, $comment, $depth, $args, $id = 0) should be compatible with Walker_Comment::start_el(&$output, $comment, $depth = 0, $args = Array, $id = 0) in /var/www/html/wp-content/themes/guru-new/guru-walker-comment.php on line 0

1 Comment

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

    Short but useful, thanks for the advice.

    Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /var/www/html/wp-content/themes/guru-new/guru-walker-comment.php on line 67