Coffeescript jQCloud handlers

2019-08-18 23:26发布

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 coffeescript version

while i < @counts.length
  x = @counts[i]
  @tag_list.push
    text: x.label
    weight: x.count
    handlers:
      click: ->
        temp = x
        ->
          alert "it worked for " + temp.label
      ()
  ++i

I get an unexpected TERMINATOR error presumably because of the (), but if you notice on the jsfiddle, removing that breaks the handler

1条回答
放我归山
2楼-- · 2019-08-18 23:26

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.

查看更多
登录 后发表回答