Observer-Pattern in JavaScript


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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');

URL: http://blog.rvi-media.de/javascript/observer-in-javascript/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.