Reputation: 22659
Consider the following CoffeeScript class:
class Event
trigger : (args...) =>
...
bind : (args...) =>
...
The use case would be:
message_received = new Event()
message_received.bind(alert)
message_received.trigger('Hello world!') # calls alert('Hello world')
Is there a way to write the Event
class in such manner that the .trigger(...)
call would have the "callable object" shortcut:
message_received('Hello world') # ?
Thank you!
Upvotes: 2
Views: 525
Reputation: 4682
Check out https://gist.github.com/shesek/4636379. It allows you to write something like that:
Event = callable class
trigger : (args...) =>
...
bind : (args...) =>
...
callable: @::trigger
Note: it relies on __proto__
(no other way to set the [[Prototype]] of functions), so you shouldn't use that if you need it to work on IE. I use it for server-side code and for intranet projects when I know users won't be using IE.
Upvotes: 1
Reputation: 348972
You need to return a function from the constructor, which is extended with the properties from the current instance (which in turn is inherit from Event.prototype
).
class Event
constructor : ->
shortcut = -> shortcut.trigger(arguments...)
for key, value of @
shortcut[key] = value
return shortcut
trigger : (args...) =>
...
bind : (args...) =>
...
Upvotes: 4