简体   繁体   中英

Emit events from a coffeescript class

I want to emit events from a coffeescript class, similar how Backbone.View does.

class Countdown extends Backbone.View
countdown = new Countdown
countdown.on "complete", ->
    something()

So without backbone.js, for example:

class Countdown extends SomeEmitter
countdown = new Countdown
countdown.start()
countdown.on "complete", ->
    something()

Atm I have something like this:

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. I don't use backbone.js in my project, so it would be silly to include it just for the Backbone.Events part. I think it should be possible to extend $({}) somehow, or something else available in 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. 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'

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM