Coffeescript jQCloud处理程序 [英] Coffeescript jQCloud handlers
问题描述
我正在尝试用coffeescript来做到这一点,
I'm trying to do this in coffeescript,
具体来说,我正在尝试向我的jQWordCloud添加处理程序,以获取所单击单词的标签
Specifically I'm trying to add handlers to my jQWordCloud to get the label for the word being clicked on
在我的coffeescript版本中
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
大概是由于(),我收到了一个意外的TERMINATOR错误,但是如果您在jsfiddle上注意到,删除该操作会破坏处理程序
I get an unexpected TERMINATOR error presumably because of the (), but if you notice on the jsfiddle, removing that breaks the handler
推荐答案
解决此问题的常用CoffeeScript方法是使用 <代码>执行代码> :
The usual CoffeeScript approach to this problem is to use do
:
使用JavaScript循环生成函数时,通常会插入一个闭包包装,以确保循环变量被封闭,并且所有生成的函数不仅共享最终值.CoffeeScript提供了
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.
然后只用普通的 for ... in
而不是 while
循环,这样就不必乱搞索引了.像这样:
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)
演示: 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)
并避免 push
调用.
演示: http://jsfiddle.net/ambiguous/3W9YC/1/
顺便说一句,您可以通过在侧边栏的 Languages 面板中选择它来在jsfiddle.net上使用CoffeeScript.
BTW, you can use CoffeeScript at jsfiddle.net by selecting it in the Languages panel in the sidebar.
这篇关于Coffeescript jQCloud处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!