{"_id":"compose","_rev":"36-e2fc93d40dc5422c96811482090688b0","name":"compose","author":{"name":"Kris Zyp"},"maintainers":[{"name":"Kris Zyp","email":"kriszyp@gmail.com"},{"name":"kriszyp","email":"kriszyp@gmail.com"}],"description":"Fast and light object composition based on mixins and traits","time":{"0.1.2":"2012-07-06T21:35:58.016Z","modified":"2022-06-13T20:13:53.472Z","created":"2012-07-06T21:34:16.570Z","0.1.0":"2012-07-06T21:35:15.255Z"},"versions":{"0.1.0":{"name":"compose","version":"0.1.0","author":{"name":"Kris Zyp"},"description":"Fast and light object composition based on mixins and traits","licenses":[{"type":"AFLv2.1","url":"http://trac.dojotoolkit.org/browser/dojo/trunk/LICENSE#L43"},{"type":"BSD","url":"http://trac.dojotoolkit.org/browser/dojo/trunk/LICENSE#L13"}],"repository":{"type":"git","url":"http://github.com/kriszyp/compose"},"dependencies":{"patr":"0.2.4"},"directories":{"lib":"./lib"},"main":"./lib/compose","mappings":{"patr":"http://github.com/kriszyp/patr/zipball/v0.2.4"},"readme":"# ComposeJS\n\nComposeJS is robust object composition built on native JavaScript mechanisms.\nComposeJS is lightweight (4K minified, 1.3K gzipped) JavaScript module based on the \nphilosophy that JavaScript's \npowerful composition mechanisms, including prototype inheritance, closures, and object \nliterals should be embraced, not contorted into an emulation of classes from other \nlanguages. It is designed to be secure, to-the-metal fast, simple, and easy to \nuse. ComposeJS builds on some of the best concepts from mixins, (traits)[http://traitsjs.org], and \ndeterministic multiple inheritance. ComposeJS assists in composing constructors and instances, providing \nshorthand and robustness for best practice JavaScript. In fact, in the documentation\nequivalent JavaScript code is provided to show exactly what is happening. \n\nThe core of ComposeJS is the Compose function. Compose()\ntakes objects or constructors as arguments and returns a new constructor. The arguments\nare composed from left to right, later arguments taken precedence (overriding) former\narguments, and any functions be executed on construction from left to right. A second\nkey function is Compose.create() which behaves like Compose(), except that\nit returns object/instances rather than constructors.\n\nIf you are using ComposeJS in a CommonJS environment, you can load it:\n<pre>\nvar Compose = require(\"compose\");\n</pre>\nOr an AMD module loader (RequireJS, Dojo, etc), you can load it:\n<pre>\ndefine([\"compose\"], function(Compose){\n  ...\n});\n</pre>\n\nIf ComposeJS is loaded as a plain script, it will create Compose as a global variable.\n\nNow to start using Compose, let's create a simple object constructor:\n<pre>\n\tWidget = Compose({\n\t\trender: function(node){\n\t\t\tnode.innerHTML = \"<div>hi</div>\";\n\t\t}\n\t});\n\tvar widget = new Widget();\n\twidget.render(node);\n</pre>\nAnd the equivalent JavaScript:\n<pre>\n\tWidget = function(){\n\t};\n\tWidget.prototype = {\n\t\trender: function(node){\n\t\t\tnode.innerHTML = \"<div>hi</div>\";\n\t\t}\n\t}\n\tvar widget = new Widget();\n\twidget.render(node);\n</pre> \nOne the features provided by ComposeJS is that it creates constructors that will work\nregardless of whether they are called with the new operator, making them less prone\nto coding mistakes. One can also choose to omit the new operator to save bytes (for faster\ndownload), although calling with the new operator is slightly faster at runtime (so\nthe faster overall would depend on how many times it is called).\n\n## Extending existing constructor\n\nTo extend our Widget we can simply include the Widget in Compose arguments: \n<pre>\n\tHelloWidget = Compose(Widget, {\n\t\tmessage: \"Hello, World\",\n\t\trender: function(){\n\t\t\tthis.node.innerHTML = \"<div>\" + this.message + \"</div>\";\n\t\t}\n\t});\n\tvar widget = new HelloWidget();\n\twidget.render(node);\n</pre> \nAnd the equivalent JavaScript:\n<pre>\n\tHelloWidget = function(){\n\t};\n\tHelloWidget.prototype = new Widget();\n\tHelloWidget.prototype.render: function(){\n\t\tthis.node.innerHTML = \"<div>hi</div>\";\n\t};\n\tvar widget = new HelloWidget();\n\twidget.render(node);\n</pre> \n\nNow let's create the constructor with a function to be executed on instantiation. Any\nfunctions in the arguments will be executed on construction, so our provided argument\ncan be used to prepare the object on instantiation:\n<pre>\n\tWidget = Compose(function(node){\n\t\tthis.node = node;\n\t},{\n\t\trender: function(){\n\t\t\tthis.node.innerHTML = \"<div>hi</div>\";\n\t\t},\n\t\tgetNode: function(){\n\t\t\treturn this.node;\n\t\t}\n\t});\n\tvar widget = new Widget(node);\n\twidget.render();\n</pre> \nAnd the equivalent JavaScript:\n<pre>\n\tWidget = function(){\n\t\tthis.node = node;\n\t};\n\tWidget.prototype = {\n\t\trender: function(node){\n\t\t\tthis.node.innerHTML = \"<div>hi</div>\";\n\t\t},\n\t\tgetNode: function(){\n\t\t\treturn this.node;\n\t\t}\n\t}\n\tvar widget = new Widget(node);\n\twidget.render();\n</pre> \n \nCompose provides can compose constructors from multiple base constructors, effectively\nproviding multiple inheritance. For example, we could create a new widget from Widget\nand Templated base constructors:\n<pre>\n\tTemplatedWidget = Compose(Widget, Templated, {\n\t  // additional functionality\n\t});\n</pre>\nAgain, latter argument's methods override former argument's methods. In this case,\nTemplated's methods will override any Widget's method of the same name. However,\nCompose is carefully designed to avoid any confusing conflict resolution in ambiguous cases.\nAutomatic overriding will only apply when later arguments have their own methods.\nIf a later argument constructor or object inherits a method, this will not automatically override\nformer base constructor's methods unless it has already overriden this method in another base\nconstructor's hierarchy. In such cases, the appropriate method must be designated in the final\nobject or else it will remain in a conflicted state. This essentially means that explicit ordering \nprovides straightforward, easy to use, method overriding, without ambiguous magical conflict \nresolution (C3MRO).\n\nWe can specify required methods that must be overriden as well. For example, we can\ndefine the Widget to require a generateHTML method:\n<pre>\n\tvar required = Compose.required;\n\tWidget = Compose({\n\t\tgenerateHTML: required,\n\t\t...\n\t});\n</pre>\n\nAnd now to extend the Widget constructor, we must provide a generateHTML method.\nFailure to do so will result in an error being thrown when generateHTML is called.\n\n## Apply to an existing object\n\nCompose can also be applied to existing objects to add/mixin functionality to that object.\nThis is done by using the standard call() or apply() function methods to define |this| for the\ncall. When Compose is applied in this way, the target object will have the methods from\nall the provide objects or constructors added to it. For example:\n<pre>\n\tvar object = {a: 1};\n\tCompose.call(object, {b: 2});\n\tobject -> {a: 1, b: 2}\n</pre>\n\nWe can use this form of Compose to add methods during construction. This is one style\nof creating instances that have private and public methods. For example, we could extend\nWidget with:\n<pre>\n\tvar required = Compose.required;\n\tWidget = Compose(Widget, function(innerHTML){\n\t\t// this will mixin the provide methods into |this|\n\t\tCompose.call(this, {\n\t\t\tgenerateHTML: function(){\n\t\t\t\treturn \"<div>\" + generateInner() + \"</div>\";\n\t\t\t}\n\t\t});\n\t\t// private function\n\t\tfunction generateInner(){\n\t\t\treturn innerHTML;\n\t\t}\n\t});\n</pre>\n\nApplying Compose can also be conveniently leveraged to make constructors that mixin properties\nfrom an object argument. This is a common pattern for constructors and allows an\ninstance to be created with preset properties provided to the constructor. This also\nalso makes it easy to have independent optional named parameters with defaults.\nWe can implement this pattern by simple having Compose be a base constructor\nfor our composition. For example, we can create a widget that extends Compose\nand therefore we can instantiate Widgets with an object argument that provides initial property settings:\n<pre>\n\tWidget = Compose(Compose, {\n\t\trender: function(){\n\t\t\tthis.node.innerHTML = \"<div>hi</div>\";\n\t\t}\n\t});\n\tvar widget = new Widget({node: byId(\"some-id\")});\n\twidget.node -> byId(\"some-id\")\n\twidget.render(); \n</pre>\nThis is a powerful way to build constructors since constructors can be created that include\nall the functionality that Compose provides, including decorators and multiple \nobjects or constructors as arguments.\n\n## Compose.create\n\nCompose.create() is another function provided by the ComposeJS library. This function\nis similar to Compose() and takes exactly the same type of arguments (any mixture \nof constructors or objects), but rather \nthan creating a constructor, it directly creates an instance object. Calling the constructor\nreturned from Compose with no argumetns and calling Compose.create act approximately \nthe same action, i.e. Compose(...)() acts the same as Compose.create(...). The main\ndifference is that Compose.create is optimized for instance creation and avoids\nunnecessary prototype creation involved in creating a constructor.\n\nCompose.create is particularly useful in conjunction with the closure-style constructors.\nA closure-style constructor (sometimes called the module pattern) can have private\nvariables and generally returns an object created using object literal syntax. \nFor base constructors that don't extend anything else, This is well-supported by native JavaScript\nthere is no need to use ComposeJS (or another library) to create a simple base constructor.\nBut for extending base constructors, Compose.create is very useful. For example,\nwe could create a base widget using this pattern (again, we can just use native JavaScript):\n<pre>\n\tWidget = function(node){ // node is a private variable\n\t\treturn {\n\t\t\trender: function(){\n\t\t\t\tnode.innerHTML = this.message;\n\t\t\t},\n\t\t\tmessage: \"Hello\"\n\t\t};\n\t};\n</pre>\nAnd now we could extend this widget, continuing to use the closure-style constructor,\nwith help from Compose.create. Here we will call base constructor, and use the returned\nbase instance to compose an extended instance. The \"node\" variable continues to stay\nprotected from direct access:\n<pre>\n\tBoldWidget = function(node){\n\t\tbaseWidget = Widget(node);\n\t\treturn Compose.create(baseWidget, {\n\t\t\trender: function(){\n\t\t\t\tbaseWidget.render(); \n\t\t\t\tnode.style.fontWeight = \"bold\";\n\t\t\t}\n\t\t});\n\t};\n</pre>\n\n## Decorators\nDecorators provides a customized way to add properties/methods to target objects.\nSeveral decorators are provided with ComposeJS:\n\n### Aspects (or Super-calls)\n\nCompose provides an aspect-oriented decorator to add functionality to existing method \ninstead of completely overriding or replacing the method. This provides super-call type \nfunctionality. The after() function allows one to add code that will be executed after\nthe base method:\n<pre>\n\tvar after = Compose.after;\n\tWidgetWithTitle = Compose(Widget, {\n\t\trender: after(function(){\n\t\t\t// called after the original render() from Widget  \n\t\t\tthis.node.insertBefore(header, this.node.firstChild);\n\t\t}\n\t});\n</pre>\n\nThe after() advice (provided function) can return a value that will be returned to the original caller. If\nnothing is returned, the inherited method's return value will be returned.\n \nThe before() function allows one to add code that will be executed before\nthe base method:\n<pre>\n\tvar before = Compose.before;\n\tBoldWidget = Compose(Widget, {\n\t\trender: before(function(){\n\t\t\t// called before the original render() from Widget  \n\t\t\tthis.node.style.fontWeight = \"bold\";\n\t\t}\n\t});\n</pre>\n\nThe before() advice can return an array that will be used as the arguments for the\ninherited function. If nothing is returned, the original calling arguments are passed to\nthe inherited function. \n\nThe around function allows one to closure around an overriden method to combine\nfunctionality. For example, we could override the render function in Widget, but still\ncall the base function:   \n<pre>\n\tvar around = Compose.around;\n\tBoldWidgetWithTitle = Compose(Widget, {\n\t\trender: around(function(baseRender){\n\t\t\t// return the new render function\n\t\t\treturn function(){\n\t\t\t\tthis.node.style.fontWeight = \"bold\";\n\t\t\t\tbaseRender.call(this);\n\t\t\t\tthis.node.insertBefore(header, this.node.firstChild);\n\t\t\t};\n\t\t});\n\t});\n</pre>\n\nYou can also apply aspects to existing instances. For example, we can add a listener\nfor each time render is called on a widget instance:\n<pre>\n\tvar widget = new Widget(node);\n\tCompose.after(widget, \"render\", function(){\n\t\tconsole.log(\"render called\");\n\t});\n</pre>\n\nYou can also use the aspect functions as methods that are applied to their instances.\nFor example, we could add the after() function as an on() method:\n<pre>\n\tvar after = Compose.after;\n\tWidgetEventEmitter = Compose(Widget, {\n\t\ton: after\n\t});\n\tvar widget = new WidgetEventEmitter(node);\n\twidget.on(\"render\", function(){\n\t\tconsole.log(\"render called\");\n\t});\n</pre>\t\n\nAll the aspect functions (before, after, and around) can be applied to existing instances or used as methods as demonstrated above.\n\n### Composition Control: Method Aliasing and Exclusion\nOne of the key capabilities of traits-style composition is control of which method to\nkeep or exclude from the different components that are being combined. The from()\ndecorator provides simple control over which method to use. We can use from() with\nthe base constructor to indicate the appropriate method to keep. For example, if we\ncomposed from Widget and Templated, we could use from() to select the save()\nmethod from Widget and render() from Templated:\n<pre>\n\tvar from = Compose.from;\n\tTemplatedWidget = Compose(Widget, Templated, {\n\t\tsave: from(Widget),\n\t\trender: from(Templated)\n\t});\n</pre>\n\nWe can also alias methods, making them available under a new name. This is very useful\nwhen we need to access multiple conflicting methods. We can provide a string argument\nthat indicates the method name to retrieve (it will be aliased to the property name that\nit is being applied to). With the string argument, the constructor argument is optional\n(defaults to whatever method would naturally be selected for the given name):\n<pre>\n\tvar from = Compose.from;\n\tTemplatedWidget = Compose(Widget, Templated, {\n\t\twidgetRender: from(Widget, \"render\"),\n\t\ttemplateRender: from(Templated, \"render\"),\n\t\tsaveTemplate: from(\"save\"),\n\t\trender: function(){\n\t\t\tthis.widgetRender();\n\t\t\tthis.templateRender();\n\t\t\t// do other stuff\n\t\t},\n\t\tsave: function(){\n\t\t\tthis.saveTemplate();\n\t\t\t//...\n\t\t}\n\t});\n</pre>\n\n### Non-enumerated methods\n\nThe dontEnum decorator can be used for non-enumerated methods (only works on JavaScript engines with ES5 support):\n<pre>\n\tvar dontEnum = Compose.dontEnum;\n\tWidgetWithTitle = Compose(Widget, {\n\t\trender: dontEnum(function(baseRender){\n\t\t\t...\n</pre>\n\n#### Note about enumeration shadow bug in IE\nNote that non-enumerable properties will not be copied from mixins (constructors/objects\nafter the first argument, the first argument inherits non-enumerable fine). Also note\nthat IE has long had a bug where creating a property that shadows a non-enumerable \nproperty (like toString, hasOwnProperty, etc) results in a non-enumerable. Some libraries\nperform extra checks for these possibly shadowed properties, but this comes at a \nsignificant cost in terms of performance and size. Since most applications don't need \nto replace these shadowed properties, they shouldn't incur this overhead/penalty. If you really do\nneed to use non-enumerable properties in mixins and want to ensure they are copied,\nit is recommended they you add these properties in constructors.\n\n### Creating Decorators\nDecorators are created by newing the Decorator constructor with a function argument\nthat is called with the property name. The function's |this| will be the target object, and\nthe function can add a property anyway it sees fit. For example, you could create a decorator:\n<pre>\n\tLogged = function(method){\n\t\treturn new Compose.Decorator(function(key){\n\t\t\tthis[key] = function(){\n\t\t\t\tconsole.log(key + \" called\");\n\t\t\t\treturn method.apply(this, arguments);\n\t\t\t}\n\t\t});\n\t});\n\tWidget = Compose({\n\t\trender: Logged(function(){\n\t\t\t...\n\t\t});\n\t});\n</pre>\n\n ","_id":"compose@0.1.0","dist":{"shasum":"1922c93f41923c5868673dcc282741244057abcf","tarball":"https://registry.npmjs.org/compose/-/compose-0.1.0.tgz","integrity":"sha512-7VgpFDwnxIE8jLntnbK9xXv05rhiT7rHuj4G3wewBbUYmmu5JhJJLdjqBzCMVNJvr15VmcfjdQWXecEKS0Ectw==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIEqm5i8dEB2b712DQJ4AloJ6N8VNwls7bJtp5sQHjN6VAiA6uOxksgVuLysIILpmak5FTEOUOqaWEfJAR6wNHlx8aQ=="}]},"scripts":{},"maintainers":[{"name":"Kris Zyp","email":"kriszyp@gmail.com"}]},"0.1.2":{"name":"compose","version":"0.1.2","author":{"name":"Kris Zyp"},"description":"Fast and light object composition based on mixins and traits","licenses":[{"type":"AFLv2.1","url":"http://trac.dojotoolkit.org/browser/dojo/trunk/LICENSE#L43"},{"type":"BSD","url":"http://trac.dojotoolkit.org/browser/dojo/trunk/LICENSE#L13"}],"repository":{"type":"git","url":"http://github.com/kriszyp/compose"},"dependencies":{"patr":"0.2.5"},"directories":{"lib":"."},"main":"./compose","mappings":{"patr":"http://github.com/kriszyp/patr/zipball/v0.2.5"},"icon":"http://icons.iconarchive.com/icons/kawsone/teneo/64/BiiBall-icon.png","readme":"# ComposeJS\n\nComposeJS is robust object composition built on native JavaScript mechanisms.\nComposeJS is lightweight (3K minified, 1K gzipped) JavaScript module based on the \nphilosophy that JavaScript's \npowerful composition mechanisms, including prototype inheritance, closures, and object \nliterals should be embraced, not contorted into an emulation of classes from other \nlanguages. It is designed to be secure, to-the-metal fast, simple, and easy to \nuse. ComposeJS builds on some of the best concepts from mixins, (traits)[http://traitsjs.org], and \ndeterministic multiple inheritance. ComposeJS assists in composing constructors and instances, providing \nshorthand and robustness for best practice JavaScript. In fact, in the documentation\nequivalent JavaScript code is provided to show exactly what is happening. \n\nThe core of ComposeJS is the Compose function. Compose()\ntakes objects or constructors as arguments and returns a new constructor. The arguments\nare composed from left to right, later arguments taken precedence (overriding) former\narguments, and any functions be executed on construction from left to right. A second\nkey function is Compose.create() which behaves like Compose(), except that\nit returns object/instances rather than constructors.\n\nIf you are using ComposeJS in a CommonJS environment, you can load it:\n<pre>\nvar Compose = require(\"compose\");\n</pre>\nOr an AMD module loader (RequireJS, Dojo, etc), you can load it:\n<pre>\ndefine([\"compose\"], function(Compose){\n  ...\n});\n</pre>\n\nIf ComposeJS is loaded as a plain script, it will create Compose as a global variable.\n\nNow to start using Compose, let's create a simple object constructor:\n<pre>\n\tWidget = Compose({\n\t\trender: function(node){\n\t\t\tnode.innerHTML = \"<div>hi</div>\";\n\t\t}\n\t});\n\tvar widget = new Widget();\n\twidget.render(node);\n</pre>\nAnd the equivalent JavaScript:\n<pre>\n\tWidget = function(){\n\t};\n\tWidget.prototype = {\n\t\trender: function(node){\n\t\t\tnode.innerHTML = \"<div>hi</div>\";\n\t\t}\n\t}\n\tvar widget = new Widget();\n\twidget.render(node);\n</pre> \nOne the features provided by ComposeJS is that it creates constructors that will work\nregardless of whether they are called with the new operator, making them less prone\nto coding mistakes. One can also choose to omit the new operator to save bytes (for faster\ndownload), although calling with the new operator is slightly faster at runtime (so\nthe faster overall would depend on how many times it is called).\n\n## Extending existing constructor\n\nTo extend our Widget we can simply include the Widget in Compose arguments: \n<pre>\n\tHelloWidget = Compose(Widget, {\n\t\tmessage: \"Hello, World\",\n\t\trender: function(){\n\t\t\tthis.node.innerHTML = \"<div>\" + this.message + \"</div>\";\n\t\t}\n\t});\n\tvar widget = new HelloWidget();\n\twidget.render(node);\n</pre> \nAnd the equivalent JavaScript:\n<pre>\n\tHelloWidget = function(){\n\t};\n\tHelloWidget.prototype = new Widget();\n\tHelloWidget.prototype.render: function(){\n\t\tthis.node.innerHTML = \"<div>hi</div>\";\n\t};\n\tvar widget = new HelloWidget();\n\twidget.render(node);\n</pre> \n\nNow let's create the constructor with a function to be executed on instantiation. Any\nfunctions in the arguments will be executed on construction, so our provided argument\ncan be used to prepare the object on instantiation:\n<pre>\n\tWidget = Compose(function(node){\n\t\tthis.node = node;\n\t},{\n\t\trender: function(){\n\t\t\tthis.node.innerHTML = \"<div>hi</div>\";\n\t\t},\n\t\tgetNode: function(){\n\t\t\treturn this.node;\n\t\t}\n\t});\n\tvar widget = new Widget(node);\n\twidget.render();\n</pre> \nAnd the equivalent JavaScript:\n<pre>\n\tWidget = function(){\n\t\tthis.node = node;\n\t};\n\tWidget.prototype = {\n\t\trender: function(node){\n\t\t\tthis.node.innerHTML = \"<div>hi</div>\";\n\t\t},\n\t\tgetNode: function(){\n\t\t\treturn this.node;\n\t\t}\n\t}\n\tvar widget = new Widget(node);\n\twidget.render();\n</pre> \n \nCompose provides can compose constructors from multiple base constructors, effectively\nproviding multiple inheritance. For example, we could create a new widget from Widget\nand Templated base constructors:\n<pre>\n\tTemplatedWidget = Compose(Widget, Templated, {\n\t  // additional functionality\n\t});\n</pre>\nAgain, latter argument's methods override former argument's methods. In this case,\nTemplated's methods will override any Widget's method of the same name. However,\nCompose is carefully designed to avoid any confusing conflict resolution in ambiguous cases.\nAutomatic overriding will only apply when later arguments have their own methods.\nIf a later argument constructor or object inherits a method, this will not automatically override\nformer base constructor's methods unless it has already overriden this method in another base\nconstructor's hierarchy. In such cases, the appropriate method must be designated in the final\nobject or else it will remain in a conflicted state. This essentially means that explicit ordering \nprovides straightforward, easy to use, method overriding, without ambiguous magical conflict \nresolution (C3MRO).\n\nWe can specify required methods that must be overriden as well. For example, we can\ndefine the Widget to require a generateHTML method:\n<pre>\n\tvar required = Compose.required;\n\tWidget = Compose({\n\t\tgenerateHTML: required,\n\t\t...\n\t});\n</pre>\n\nAnd now to extend the Widget constructor, we must provide a generateHTML method.\nFailure to do so will result in an error being thrown when generateHTML is called.\n\n## Apply to an existing object\n\nCompose can also be applied to existing objects to add/mixin functionality to that object.\nThis is done by using the standard call() or apply() function methods to define |this| for the\ncall. When Compose is applied in this way, the target object will have the methods from\nall the provide objects or constructors added to it. For example:\n<pre>\n\tvar object = {a: 1};\n\tCompose.call(object, {b: 2});\n\tobject -> {a: 1, b: 2}\n</pre>\n\nWe can use this form of Compose to add methods during construction. This is one style\nof creating instances that have private and public methods. For example, we could extend\nWidget with:\n<pre>\n\tvar required = Compose.required;\n\tWidget = Compose(Widget, function(innerHTML){\n\t\t// this will mixin the provide methods into |this|\n\t\tCompose.call(this, {\n\t\t\tgenerateHTML: function(){\n\t\t\t\treturn \"<div>\" + generateInner() + \"</div>\";\n\t\t\t}\n\t\t});\n\t\t// private function\n\t\tfunction generateInner(){\n\t\t\treturn innerHTML;\n\t\t}\n\t});\n</pre>\n\nApplying Compose can also be conveniently leveraged to make constructors that mixin properties\nfrom an object argument. This is a common pattern for constructors and allows an\ninstance to be created with preset properties provided to the constructor. This also\nalso makes it easy to have independent optional named parameters with defaults.\nWe can implement this pattern by simple having Compose be a base constructor\nfor our composition. For example, we can create a widget that extends Compose\nand therefore we can instantiate Widgets with an object argument that provides initial property settings:\n<pre>\n\tWidget = Compose(Compose, {\n\t\trender: function(){\n\t\t\tthis.node.innerHTML = \"<div>hi</div>\";\n\t\t}\n\t});\n\tvar widget = new Widget({node: byId(\"some-id\")});\n\twidget.node -> byId(\"some-id\")\n\twidget.render(); \n</pre>\nThis is a powerful way to build constructors since constructors can be created that include\nall the functionality that Compose provides, including decorators and multiple \nobjects or constructors as arguments.\n\n## Compose.create\n\nCompose.create() is another function provided by the ComposeJS library. This function\nis similar to Compose() and takes exactly the same type of arguments (any mixture \nof constructors or objects), but rather \nthan creating a constructor, it directly creates an instance object. Calling the constructor\nreturned from Compose with no arguments and calling Compose.create act approximately \nthe same action, i.e. Compose(...)() acts the same as Compose.create(...). The main\ndifference is that Compose.create is optimized for instance creation and avoids\nunnecessary prototype creation involved in creating a constructor.\n\nCompose.create is particularly useful in conjunction with the closure-style constructors.\nA closure-style constructor (sometimes called the module pattern) can have private\nvariables and generally returns an object created using object literal syntax. \nFor base constructors that don't extend anything else, This is well-supported by native JavaScript\nthere is no need to use ComposeJS (or another library) to create a simple base constructor.\nBut for extending base constructors, Compose.create is very useful. For example,\nwe could create a base widget using this pattern (again, we can just use native JavaScript):\n<pre>\n\tWidget = function(node){ // node is a private variable\n\t\treturn {\n\t\t\trender: function(){\n\t\t\t\tnode.innerHTML = this.message;\n\t\t\t},\n\t\t\tmessage: \"Hello\"\n\t\t};\n\t};\n</pre>\nAnd now we could extend this widget, continuing to use the closure-style constructor,\nwith help from Compose.create. Here we will call base constructor, and use the returned\nbase instance to compose an extended instance. The \"node\" variable continues to stay\nprotected from direct access:\n<pre>\n\tBoldWidget = function(node){\n\t\tbaseWidget = Widget(node);\n\t\treturn Compose.create(baseWidget, {\n\t\t\trender: function(){\n\t\t\t\tbaseWidget.render(); \n\t\t\t\tnode.style.fontWeight = \"bold\";\n\t\t\t}\n\t\t});\n\t};\n</pre>\n\n##Constructor.extend\nConstructors created with Compose also include a \"static\" extend method that can be\nused for convenience in creating subclasses. The extend method behaves the same\nas Compose with the target class being the first parameter:\n<pre>\n\tMyClass = Compose(...);\n\tSubClass = MyClass.extend({\n\t\tsubMethod: function(){}\n\t});\n\t// same as:\n\tSubClass = Compose(MyClass,{\n\t\tsubMethod: function(){}\n\t});\n</pre>\n\n## Decorators\nDecorators provides a customized way to add properties/methods to target objects.\nSeveral decorators are provided with ComposeJS:\n\n### Aspects (or Super-calls)\n\nCompose provides an aspect-oriented decorator to add functionality to existing method \ninstead of completely overriding or replacing the method. This provides super-call type \nfunctionality. The after() function allows one to add code that will be executed after\nthe base method:\n<pre>\n\tvar after = Compose.after;\n\tWidgetWithTitle = Compose(Widget, {\n\t\trender: after(function(){\n\t\t\t// called after the original render() from Widget  \n\t\t\tthis.node.insertBefore(header, this.node.firstChild);\n\t\t}\n\t});\n</pre>\n\nThe after() advice (provided function) can return a value that will be returned to the original caller. If\nnothing is returned, the inherited method's return value will be returned.\n \nThe before() function allows one to add code that will be executed before\nthe base method:\n<pre>\n\tvar before = Compose.before;\n\tBoldWidget = Compose(Widget, {\n\t\trender: before(function(){\n\t\t\t// called before the original render() from Widget  \n\t\t\tthis.node.style.fontWeight = \"bold\";\n\t\t}\n\t});\n</pre>\n\nThe before() advice can return an array that will be used as the arguments for the\ninherited function. If nothing is returned, the original calling arguments are passed to\nthe inherited function. If Compose.stop is returned, the inherited function will not be \ncalled.\n\nThe around function allows one to closure around an overriden method to combine\nfunctionality. For example, we could override the render function in Widget, but still\ncall the base function:   \n<pre>\n\tvar around = Compose.around;\n\tBoldWidgetWithTitle = Compose(Widget, {\n\t\trender: around(function(baseRender){\n\t\t\t// return the new render function\n\t\t\treturn function(){\n\t\t\t\tthis.node.style.fontWeight = \"bold\";\n\t\t\t\tbaseRender.call(this);\n\t\t\t\tthis.node.insertBefore(header, this.node.firstChild);\n\t\t\t};\n\t\t});\n\t});\n</pre>\n\n### Composition Control: Method Aliasing and Exclusion\nOne of the key capabilities of traits-style composition is control of which method to\nkeep or exclude from the different components that are being combined. The from()\ndecorator provides simple control over which method to use. We can use from() with\nthe base constructor to indicate the appropriate method to keep. For example, if we\ncomposed from Widget and Templated, we could use from() to select the save()\nmethod from Widget and render() from Templated:\n<pre>\n\tvar from = Compose.from;\n\tTemplatedWidget = Compose(Widget, Templated, {\n\t\tsave: from(Widget),\n\t\trender: from(Templated)\n\t});\n</pre>\n\nWe can also alias methods, making them available under a new name. This is very useful\nwhen we need to access multiple conflicting methods. We can provide a string argument\nthat indicates the method name to retrieve (it will be aliased to the property name that\nit is being applied to). With the string argument, the constructor argument is optional\n(defaults to whatever method would naturally be selected for the given name):\n<pre>\n\tvar from = Compose.from;\n\tTemplatedWidget = Compose(Widget, Templated, {\n\t\twidgetRender: from(Widget, \"render\"),\n\t\ttemplateRender: from(Templated, \"render\"),\n\t\tsaveTemplate: from(\"save\"),\n\t\trender: function(){\n\t\t\tthis.widgetRender();\n\t\t\tthis.templateRender();\n\t\t\t// do other stuff\n\t\t},\n\t\tsave: function(){\n\t\t\tthis.saveTemplate();\n\t\t\t//...\n\t\t}\n\t});\n</pre>\n\n### Non-enumerated methods\n\nThe dontEnum decorator can be used for non-enumerated methods (only works on JavaScript engines with ES5 support):\n<pre>\n\tvar dontEnum = Compose.dontEnum;\n\tWidgetWithTitle = Compose(Widget, {\n\t\trender: dontEnum(function(baseRender){\n\t\t\t...\n</pre>\n\n#### Note about enumeration shadow bug in IE\nNote that non-enumerable properties will not be copied from mixins (constructors/objects\nafter the first argument, the first argument inherits non-enumerable fine). Also note\nthat IE has long had a bug where creating a property that shadows a non-enumerable \nproperty (like toString, hasOwnProperty, etc) results in a non-enumerable. Some libraries\nperform extra checks for these possibly shadowed properties, but this comes at a \nsignificant cost in terms of performance and size. Since most applications don't need \nto replace these shadowed properties, they shouldn't incur this overhead/penalty. If you really do\nneed to use non-enumerable properties in mixins and want to ensure they are copied,\nit is recommended they you add these properties in constructors.\n\n### Creating Decorators\nDecorators are created by newing the Decorator constructor with a function argument\nthat is called with the property name. The function's |this| will be the target object, and\nthe function can add a property anyway it sees fit. For example, you could create a decorator:\n<pre>\n\tLogged = function(method){\n\t\treturn new Compose.Decorator(function(key){\n\t\t\tthis[key] = function(){\n\t\t\t\tconsole.log(key + \" called\");\n\t\t\t\treturn method.apply(this, arguments);\n\t\t\t}\n\t\t});\n\t});\n\tWidget = Compose({\n\t\trender: Logged(function(){\n\t\t\t...\n\t\t});\n\t});\n</pre>\n\n ","_id":"compose@0.1.2","dist":{"shasum":"d556f55d0a91399df4227945c1bd96030310fe7c","tarball":"https://registry.npmjs.org/compose/-/compose-0.1.2.tgz","integrity":"sha512-xb8nY0ydqgm688NAiQBogZzKwG50h+Zim2QnZAbdSxTC7akMxQ3j6hO4Fc++97JftRAWkJP+SFdiYcCeZedVTg==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQCU7fW4cl+da9B0CYSyF+qwQI46CgZ49CP0vvwZtmM2OAIgPHxGf3P7VH/I2I5Wk/YUbce0ufH1sReWTWGinbXuZps="}]},"scripts":{},"maintainers":[{"name":"Kris Zyp","email":"kriszyp@gmail.com"}]}},"dist-tags":{"latest":"0.1.2"},"repository":{"type":"git","url":"http://github.com/kriszyp/compose"},"users":{"samuelg":true,"scottfreecode":true}}