A
A
Aliceloves2014-05-16 17:11:33
JavaScript
Aliceloves, 2014-05-16 17:11:33

How to implement the publish–subscribe pattern at the class level?

You must implement the publish-subscribe pattern at the class level.
I.e:

class Animal
  constructor: () ->
    # храним здесь подписчиков экземпляра
    @pings = []

  ping: (event, func) -> 
    # подписываемся на события экземпляра

  pong: (event, data) ->
    # перебираем и вызываем всех подписчиков экземпляра и !!класса!!


# храним здесь подписчиков класса
Animal.pings = []

Animal.ping = (event, func) ->
  # подписываемся на события класса (т.е. !!на события всех экземпляров!! )


# Подписываемся на событие 'say'
Animal.ping('say', alert)

The problems start when the class is inherited:
# Наследуем Animal
class Dog extends Animal

# Подписываемся на общее для класса Dog событие 'pee'
Dog.ping('pee', peeFunc)

# И на этом моменте всё ломается: вызывается функция peeFunc, которая никакого отношения к Animal не имеет.
animal = new Animal()
animal.pong('pee', {})

Since JavaScript is passing pointers to objects, not...
What's the best way to implement it? Now I settled on the .separate() function, which I call immediately after inheriting from Animal and copy the pings array of the parent class.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mike, 2014-06-25
Ross

I understand that the list of events is in the class prototype which is available to all instances.
Dog.prototype refers to Animal which contains a list of all events for all classes.
Apparently, Dog needs to create its own pings property and store only events of this class there.
PS: I don’t write for coffee.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question