Monday, 11 February 2013

Generic Javascript Proxy object for Firebase

If you've come across the same issue as me then sometimes you want to act like you have an object but you really only have its Firebase Reference. This is some fairly generic code for proxying the object.
var FirebaseProxy = function(classToProxy, firebaseRef) {
  var key,
      self = this;
      
  self.proxy = classToProxy;
  self.firebaseRef = firebaseRef;
 
  for (key in self.proxy.prototype) {
    if (typeof self.proxy.prototype[key] === 'function') {
      // don't over-write our own properties
      if (key === "proxy" || key === "firebaseRef") {
        console.warning("Name clash in FirebaseProxy. Key = " + key);
        continue;        
      }
      
      (function(inner_key) {
        self[inner_key] = function () {
          var args = arguments;
          
          self.firebaseRef.once('value', function(data) {
            var proxiedInstance = new self.proxy();
            
            if (typeof proxiedInstance.init === 'function') {
              proxiedInstance.init(self.firebaseRef, data.val());
            }
            
            proxiedInstance[inner_key].apply(proxiedInstance, args);
          });
        }
          
      })(key);        
    }
  }
};