Coffeescript jQCloud handlers

余生长醉 提交于 2019-12-24 22:32:02

问题


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:


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.



来源:https://stackoverflow.com/questions/18047666/coffeescript-jqcloud-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!