Skip to content

Instantly share code, notes, and snippets.

@gmoeck
Created June 12, 2012 16:29
Show Gist options
  • Save gmoeck/2918538 to your computer and use it in GitHub Desktop.
Save gmoeck/2918538 to your computer and use it in GitHub Desktop.
Extremely Late binding
/* Imagine that you have a publish/subscribe system where you want a publisher to publish messages to a set of subscribers. There are two ways that you can specify the message to send, with a function to call on the object, and with a string.*/
//Functional subscription (Essentially a partially applied function)
publisher.addListener('someEvent', subscriber.someResult, subscriber);
//This ends up having code that looks something like this:
addListener: function(eventName, functionToCall, subscriber) {
this._events[eventName].push({functionToCall: functionToCall, context: subscriber});
},
...
invoke: function(eventName, data) {
this._events[eventName].forEach(function(eventData) {
eventData.functionToCall.call(eventData.context, data);
});
}
//String subscription (Essentially a late binding message)
publisher.addListener('someEvent', 'someResult', subscriber);
//This ends up having code that looks something like this:
addListener: function(eventName, messageToSend, subscriber) {
this._events[eventName].push({subscriber: subscriber, message: messageToSend});
},
...
invoke: function(eventName, data) {
this._events[eventName].forEach(function(eventData) {
eventData.subscriber[eventData.message](data);
});
}
/*In the first example, the binding of the function takes place at subscription time, whereas in the latter it takes place at invocation time.
Now imagine that the subscriber internally did something like a state machine where the message means different things depending on which state the object is in.
In ruby one might accomplish this by using message_missing, but in JS people usually do this by simply replacing the function on the object dynamically when the state changes.
In either way when I subscribed to the event within one state, and then a state transition occurs the first method will still call the original function rather than the current function.*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment