Created
July 17, 2009 16:23
-
-
Save swannodette/149141 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function.implement({ | |
decorate: function() | |
{ | |
var decorators = $A(arguments); | |
var resultFn = this; | |
decorator = decorators.pop(); | |
while(decorator) | |
{ | |
resultFn = decorator(resultFn); | |
decorator = decorators.pop(); | |
} | |
return resultFn; | |
} | |
}); | |
/* | |
var verify1 = function(fn) { | |
return function() { | |
var args = $A(arguments); | |
if($type(args[0]) != "string") | |
{ | |
throw new Error("First arg is not a string"); | |
} | |
else | |
{ | |
console.log("verify1 decorator run") | |
return fn.apply(this, args); | |
} | |
} | |
}; | |
var verify2 = function(fn) { | |
return function() { | |
var args = $A(arguments); | |
if($type(args[1]) != "string") | |
{ | |
throw new Error("Second arg is not a string"); | |
} | |
else | |
{ | |
console.log("verify2 decorator run") | |
return fn.apply(this, args); | |
} | |
} | |
}; | |
// add type checking of first and second arguments to myfn! | |
var myfn = function(argA, argB) { | |
console.log("Hello from myfn! argA " + argA + ", argB " + argB); | |
}.decorate(verify1, verify2); | |
// do the same for a class method | |
var MyClass = new Class({ | |
name: "MyClass", | |
aMethod: function(argA, argB) { | |
console.log("Hello from myfn! argA " + argA + ", argB " + argB); | |
console.log(this.name); | |
}.decorate(verify1, verify2) | |
}); | |
var instance = new MyClass(); | |
instance.aMethod("foo", "bar"); // works | |
try | |
{ | |
instance.aMethod(2, "bar"); | |
} | |
catch(err) | |
{ | |
console.log(err); | |
} | |
try | |
{ | |
instance.aMethod("foo", 2); | |
} | |
catch(err) | |
{ | |
console.log(err); | |
} | |
myfn("foo", "bar"); // works | |
try | |
{ | |
myfn(2, "bar"); // verify1 throws exception! | |
} | |
catch(err) | |
{ | |
console.log(err); | |
} | |
try | |
{ | |
myfn("foo", 2); // verify2 throws exception! | |
} | |
catch(err) | |
{ | |
console.log(err); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment