Skip to content Skip to sidebar Skip to footer

Coffeescript JQCloud Handlers

I'm trying to do this in coffeescript, http://jsfiddle.net/Q6348/8/ Specifically I'm trying to add handlers to my jQWordCloud to get the label for the word being clicked on In my c

Solution 1:

The usual CoffeeScript approach to this problem is to use do:

When using a JavaScript loop to generate functions, it's common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don't just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.

Then just use a plain for ... in instead of the while loop so that you don't have to muck around with the indexes; something more like this:

for o in stuff
  do (o) ->
    tag_list.push
      text: o.NAME
      weight: o.COUNT
      html:
        title: "#{o.COUNT} varieties"
      handlers:
        click: -> console.log("it worked for", o)

Demo: http://jsfiddle.net/ambiguous/3W9YC/

Or you could use a loop comprehension like this:

tag_list = for o in stuff
  do (o) ->
    text: o.NAME
    weight: o.COUNT
    html:
      title: "#{o.COUNT} varieties"
    handlers:
      click: -> console.log("it worked for", o)

and avoid the push calls.

Demo: http://jsfiddle.net/ambiguous/3W9YC/1/

BTW, you can use CoffeeScript at jsfiddle.net by selecting it in the Languages panel in the sidebar.


Post a Comment for "Coffeescript JQCloud Handlers"