Posted By

magna on 11/10/11


Tagged

observer designpattern


Versions (?)

Observer-Pattern in JavaScript


 / Published in: JavaScript
 

URL: http://blog.rvi-media.de/javascript/observer-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');

Report this snippet  

You need to login to post a comment.