I have a great many loops in my coffeescript that iterate over a collection of DOM elements, and execute more jQuery. These functions tend to look like this:
$('.iterable.object').each ->
$(@).doThis
$(@).doThat
## More complicated usage
$(@).jqueryPluginCall
x: $(@).data('attr1')
x: $(@).data('attr2')
## More complicated usage
$(@).children('ul.animateable').each ->
if $(@).data('animation') is "fancy"
$(@).animate fancy: animation
else
$(@).animate simple: animation
$(@).focus(
->
$(@).animate some: more
, ->
$(@).animate even: more
) ## Or however you do double callbacks
I made about 3 typos entering the $(@).
's again and again, and it's becoming a pain.
There isn't a shortcut syntax for $(@)
? It's kind of a pain to type and seems like a pretty common syntax. It'd be cool if it operated similarly to @
as an automated function caller, like &doThis
instead of &.doThis
.
EDIT: I'd like to be able to define an alias right in javascript after jQuery loads that responds with the DOM element when called &
and chains to methods &doThis
, rather than at the top of each loop the way @bennedich suggests below.
How about function chaining:
$('.iterable.object').each ->
$(@)
.doThis()
.doThat()
Or storing $(@)
to a variable:
$('.iterable.object').each ->
t = $(@)
t.doThis()
t.doThat()
Or a combination of the two. Last thing I can think of is IDE snippets, eg textmate will let you configure letter+TAB be replaced by $(@)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.