[英]Emit events from a coffeescript class
I want to emit events from a coffeescript class, similar how Backbone.View does. 我想从coffeescript类发出事件,类似于Backbone.View这样做。
class Countdown extends Backbone.View
countdown = new Countdown
countdown.on "complete", ->
something()
So without backbone.js, for example: 因此,例如,如果没有ribs.js:
class Countdown extends SomeEmitter
countdown = new Countdown
countdown.start()
countdown.on "complete", ->
something()
Atm I have something like this: Atm我有这样的事情:
class SomeEmitter
events: $({})
#So I need to countdown.events.on "complete"
But this probally could be refactored somehow, so I emit events from the countdown instance instead of countdown.events. 但这可能可以通过某种方式进行重构,因此我从countdown实例而不是countdown.events发出事件。 I don't use backbone.js in my project, so it would be silly to include it just for the Backbone.Events part.
我不在我的项目中使用bone.js,因此仅将其包含在Backbone.Events部分中是很愚蠢的。 I think it should be possible to extend $({}) somehow, or something else available in jquery (jQuery.Event?)
我认为应该可以以某种方式扩展$({})或在jquery中使用其他可用方式(jQuery.Event?)。
Update: 更新:
I think I'll go something on the line of: 我想我会采取以下行动:
class SomeEmitter
constructor: ->
@events = ${{})
on: (eventName, cb) =>
@events.on eventName, cb
trigger: (eventName) =>
@events.trigger eventName
The reason I don't use Backbone.Events (or look at the code and copy pieces) is because I have jQuery at my disposal with a fully working trigger and on method. 我不使用Backbone.Events(或查看代码和复制片段)的原因是因为我可以使用jQuery,并且触发器和on方法都可以正常工作。 So it should be possible extending that, instead of writing my own emitter.
因此应该可以扩展它,而不是编写自己的发射器。
You could do something as simple as this. 您可以做这样简单的事情。
class SomeEmitter
constructor: ->
@events = complete: []
on: (eventName, cb) =>
@events[eventName].push(cb)
startCountdown: =>
# countdown logic here
for fx in @events.complete
fx()
class Countdown extends SomeEmitter
countdown = new Countdown()
countdown.on 'complete', -> console.log 'done'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.