Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. const events = {
  2. topics: {},
  3. subscribe: function(topic, listener) {
  4. if(!this.topics.hasOwnProperty(topic)) {
  5. this.topics = {
  6. ...this.topics,
  7. [topic]: []
  8. }
  9. }
  10. let index = this.topics[topic].push(listener) -1;
  11. const remove = function(topic) {
  12. delete this.topics[topic][index]
  13. }.bind(this)
  14. return remove;
  15. },
  16. publish: function(topic, info) {
  17. this.topics[topic].forEach(fn => {
  18. fn(info)
  19. })
  20. }
  21. }
  22.  
  23. // TEST
  24.  
  25. const remove = events.subscribe('test', (info) => console.log(info))
  26.  
  27. events.publish('test', '1')
  28. events.publish('test', '2')
  29. events.publish('test', '3')
  30. events.publish('test', '4')
  31.  
  32. remove('test')
  33.  
  34. events.publish('test', '5')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement