Skip to content

Instantly share code, notes, and snippets.

@Yuffster
Created December 27, 2009 09:15
Show Gist options
  • Select an option

  • Save Yuffster/264221 to your computer and use it in GitHub Desktop.

Select an option

Save Yuffster/264221 to your computer and use it in GitHub Desktop.
//Listener class executes a logging function each time a method is called.
var Spy = new Class({
__spies: {},
spyOn: function(mth, fn) {
this.__spies[mth] = this[mth];
this[mth] = function() {
var rtrn = this.__spies[mth].attempt(arguments);
fn(rtrn, arguments);
return rtrn;
};
},
spyOff: function(mth) {
this[mth] = this.__spies[mth];
}
});
//Ridiculous example use...
var Adder = new Class({
addThings: function(var1, var2) { return var1+var2; }
});
Adder.implement(Spy);
var adder = new Adder();
adder.spyOn('addThings', function(rtrn, args) {
console.log("addThings returned "+rtrn);
console.log(args);
});
//Logs: addThings returned 5, [2, 3]
adder.addThings(2, 3);
adder.spyOff('addThings');
adder.addThings(2, 3); //Returns 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment