evfwcqcg
evfwcqcg

Reputation: 16345

Avoiding boilerplate code when handling events (Backbone, CoffeeScript)

Consider the following example http://jsfiddle.net/YmWW2/.

How can I avoid redundant methods like execFoo, execBar, execBaz and pass string like "foo" directly to exec method?

events:
    "click a#foo" : "execFoo"
    "click a#bar" : "execBar"
    "click a#baz" : "execBaz"

execFoo: -> @exec "foo"
execBar: -> @exec "bar"
execBaz: -> @exec "baz"

exec: (x) -> alert x

Upvotes: 0

Views: 106

Answers (1)

Dhruv
Dhruv

Reputation: 1400

If I'm understanding your question correctly, you can get the 'foo', 'bar' information by examining the event object that jquery passes to click handlers.

For example, the following snippet should alert the id attribute of any link that gets clicked.

events:
  'click a' : 'exec'

exec: (event) ->
  clickedLink = $(event.target)
  alert(clickedLink.id())

Upvotes: 1

Related Questions