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);
}
}
};
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.
Subscribe to:
Post Comments (Atom)
This looks very intriguing, but my tiny little creative-oriented brain can't seem to wrap around the use case.
ReplyDeleteDo you have an example of a problem this solved for you? It would help me kick start my creative synapses and really apply this idea.
No problem. The scenario I am using for testing Firebase is an online game grid. Essentially, it is made up of two components: the grid itself plus the tokens that can be moved around the grid.
DeleteI am storing the tokens as part of the grid, in Firebase terms. The issue I was facing is that when a token is moved by the user I want to update the grid, which means the token needs to have a link back to the grid. This is quite easy to do if you store a Firebase reference to the grid within the token itself. Then, when a token moves, you can find the grid reference, fetch the grid and update it.
Using the proxy I can do something like the following, cutting out a couple of steps.
var gridProxy = new FirebaseProxy(Grid, token.gridRef);
gridProxy.moveToken(token, newLocation);
Does that make sense?
This comment has been removed by the author.
DeleteIt looks like the proxied version of a class always loads its latest state before calling any of its functions. So is this sort of like an alternative to using .on() to update your game model?
DeleteIf I understand you correctly, yes.
ReplyDeleteI use the proxy and .once to update the model after a player-driven event. I use .on to then render the game when the model changes.