nextwebgen.com

The Next Generation Web Now

Transitioning from Java Classes to JavaScript Prototypes

Filed under: Web 2.0 News — Dion Almaer at 8:40 am on Wednesday, October 31, 2007

To class or not to class, that has been a question than many developers have faced as they came from class based OO worlds into the Prototype Oriented world of JavaScript. Much pain has endured for those that try to contort it.

Peter Michaux has detailed transitioning from Java Classes to JavaScript prototypes by looking at the Observer/Observable pattern and showing various implementations in Java and JavaScript ending up with his favourite mixin-able solution:

JAVASCRIPT:

  1.  
  2. var observablize;
  3.  
  4. (function() {
  5.  
  6.     var observable = {
  7.  
  8.       addObserver: function(observer) {
  9.           if (!this.observers) {
  10.               this.observers = [];
  11.           }
  12.           this.observers.push(observer);
  13.       },
  14.  
  15.       notifyObservers: function() {
  16.           for (var i=0; i<this.observers.length; i++) {
  17.               this.observers[i].update();
  18.           }
  19.       }
  20.      
  21.     };
  22.    
  23.     observablize = function (subject) {
  24.         for (var p in observable) {
  25.             subject[p] = observable[p];
  26.         }
  27.     }
  28.    
  29. })();
  30.  
  31. // —————————
  32.  
  33. function WeatherModel() {}
  34.  
  35. observablize(WeatherModel.prototype);
  36.  
  37. WeatherModel.prototype.setTemperature = function(temp) {
  38.     this.temp = temp;
  39.     this.notifyObservers();
  40. };
  41.  
  42. WeatherModel.prototype.getTemperature = function() {
  43.     return this.temp;
  44. };
  45.  
  46. // —————————
  47.  
  48. function CurrentConditionsView(model) {
  49.     this.model = model;
  50.     model.addObserver(this);
  51. }
  52.  
  53. CurrentConditionsView.prototype.update = function() {
  54.     alert(this.model.getTemperature());
  55. };
  56.  
  57. // —————————
  58.  
  59. var victoriaWeather = new WeatherModel();
  60. var victoriaNews = new CurrentConditionsView(victoriaWeather);
  61.  
  62. victoriaWeather.setTemperature(15.3);
  63. victoriaWeather.setTemperature(17.0);
  64. victoriaWeather.setTemperature(14.7);
  65.  
Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blogmarks
  • del.icio.us
  • De.lirio.us
  • digg
  • NewsVine
  • YahooMyWeb

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>