mituri

[JS] Wzorzec observer

Apr 19th, 2018
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. console.clear();
  2. var cl = function(text){ console.log(text); }
  3.  
  4. var Users = {
  5. list: [],
  6. listeners: {},
  7.  
  8. add: function(name) {
  9. this.list.push({name: name});
  10. this.dispatch("user-added");
  11. },
  12. on: function(eventName, listener) {
  13. if(!this.listeners[eventName]) this.listeners[eventName] = [];
  14. this.listeners[eventName].push(listener);
  15. },
  16. dispatch: function(eventName) {
  17. if (this.listeners[eventName]) {
  18. var i, max = this.listeners[eventName].length;
  19. for (i = 0; i < max; ++i){
  20. this.listeners[eventName][i](this);
  21. }
  22. }
  23. },
  24. numOfAddedUsers: function() {
  25. return this.list.length;
  26. }
  27. }
  28.  
  29. Users.on(
  30. "user-added",
  31. function(){
  32. cl(Users.numOfAddedUsers());
  33. }
  34. );
  35.  
  36. Users.add("Casimir");
  37. Users.add("Zygmunt");
Add Comment
Please, Sign In to add comment