Permalink
Browse files

Added more accurate docs and tests for decorators, refs #16

  • Loading branch information...
1 parent 49502c6 commit e247957d59efb4966b8f94e964202b93022513b4 @kriszyp committed Aug 15, 2012
Showing with 45 additions and 9 deletions.
  1. +19 −8 README.md
  2. +26 −1 test/compose.js
View
@@ -387,23 +387,34 @@ since this disagree, it is considered ambiguous. Note that these are all conflic
### Creating Decorators
Decorators are created by newing the Decorator constructor with a function argument
that is called with the property name. The function's |this| will be the target object, and
-the function can add a property anyway it sees fit. For example, you could create a decorator:
+the function can add a property anyway it sees fit. For example, you could create a decorator
+that would explicitly override another methods, and fail if an existing method as not there.
<pre>
- Logged = function(method){
+ overrides = function(method){
return new Compose.Decorator(function(key){
- this[key] = function(){
- console.log(key + " called");
- return method.apply(this, arguments);
+ var baseMethod = this[key];
+ if(!baseMethod){
+ throw new Error("No method " + key + " exists to override");
}
+ this[key] = method;
});
- });
+ };
+
Widget = Compose({
- render: Logged(function(){
+ render: function(){
...
- });
+ }
+ });
+ SubWidget = Compose(Widget, {
+ render: overrides(function(){
+ ...
+ })
});
</pre>
+In addition, the Decorator function accepts a second argument, which is the function
+that would be executed if the decorated method is directly executed and does not override another method.
+
### Security
By default Compose will add a constructor property to your constructor's prototype to make
the constructor available from instances:
View
@@ -372,7 +372,32 @@ exports.testAdvice = function() {
assert.deepEqual(order, [0]);
};
-
+exports.testDecorator = function(){
+ var order = [];
+ overrides = function(method){
+ return new Compose.Decorator(function(key){
+ var baseMethod = this[key];
+ if(!baseMethod){
+ throw new Error("No method " + key + " exists to override");
+ }
+ this[key] = method;
+ });
+ };
+
+ Widget = Compose({
+ render: function(){
+ order.push("render");
+ }
+ });
+ SubWidget = Compose(Widget, {
+ render: overrides(function(){
+ order.push("sub render")
+ })
+ });
+ widget = new SubWidget();
+ widget.render();
+ assert.deepEqual(order, ["sub render"]);
+}
if (require.main === module)
require("patr/runner").run(exports);

0 comments on commit e247957

Please sign in to comment.