(JavaScript) Observer-Pattern in JavaScript

Could be improved by passing an event instead of a simple payload.

  1. /** origin: http://blog.rvi-media.de/javascript/observer-in-javascript/
  2.  */  
  3. var Observer = function() {
  4.         this.listeners = [];
  5.         this.add = function(callback) {
  6.                 this.listeners.push(callback);
  7.         };
  8.         this.remove = function(callback) {
  9.                 /* TODO! ;) */
  10.         };
  11.         this.update = function(payload) {
  12.                 for (i in this.listeners)
  13.                         this.listeners[i](payload);
  14.         };
  15. };
  16.  
  17. var o = new Observer();
  18. o.add(function(payload){document.writeln(payload);});
  19. o.add(function(payload){alert(payload);});
  20. o.update(‘foo’);
  21. o.update(‘bar’);
This entry was posted in JavaScript and tagged , , , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?