If Mozilla used ruby instead of JavaScript, implementing our listener would be cake:
class MockObject
def method_missing(symbol, *args)
s = symbol.to_s + "(" + args.join(", ") + ")"
alert s
end
end<br/>
## example usage
m = MockObject.new<br/>
# When I make the call:
m.one_of_the_eight_listener_methods(:an_item, :a_property, :whatever_else)<br/>
# I'm alerted with the string:
"one_of_the_eight_listener_methods(an_item, a_property, whatever_else)"
Unfortunately JavaScript doesn’t have method_missing. We can sort of simulate it using a custom MockObject class. Unfortunately, we need to explicitly name the methods (not naming is half the point to method_missing in the first place). Still, this little MockObject will serve me well.
function MockObject(methods) {
methods = methods.split(/[ \t\n]+/)
for (var i = 0; i < methods.length; ++i) {
this[methods[i]] = methodWrapper(methods[i])
}
function methodWrapper(method) {
return function() {
var args = [].concat(arguments)
var s = method + "(" + args.join(", ") + ")"
alert(s)
}
}
}<br/>
/* example usage */
m = new MockObject('oneOfTheEightListenerMethods anotherOne theRest')<br/>
// When I make the call:
m.oneOfTheEightListenerMethods('an item', 'a property', 'whatever else')<br/>
// I'm alerted with the string:
"oneOfTheEightListenerMethods(an item, a property, whatever else)"
Commentary