jquery - How to use Chaining with Nested, Revealing Module Patterns in JavaScript? -
i'm struggling head around couple of js patterns joined together: revealing module pattern, , chaining pattern.
what ideally able invoke multiple methods single initialising function this:
components .loader() .menu() .toolbar();
and works long methods define publicly return this;
.
things start go wrong when need nest revealing module patterns in order expose deeper methods invoked outside of initialisation this:
components .menu .close();
the problem doing menu
no longer returns components
, instead returns it's child methods means breaks chain @ point. here "complete" example illustrate try achieve:
var components = function () { var loader = function () { console.log("components.loader initialisation"); return this; } var menu = function () { console.log("components.menu initialisation"); var open = function () { console.log("components.menu.open"); return this; } var close = function () { console.log("components.menu.close"); return this; } return { open: open, close: close } }(); var toolbar = function () { console.log("components.toolbar initialisation"); return this; } return { loader: loader, menu: menu(), toolbar: toolbar } }(); $(function () { components .loader() .menu() .toolbar(); components .menu .open(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
so guess question is, how can use; nested, revealing modules , chaining (if @ possible)?
var components = (function () { var loader = function () { console.log("components.loader initialisation"); return this; }; var menu = function () { var menu = function () { console.log("components.menu initialisation"); return this; }; menu.open = function () { console.log("components.menu.open"); return this; }; menu.close = function () { console.log("components.menu.close"); return this; }; return menu; }; var toolbar = function () { console.log("components.toolbar initialisation"); return this; }; return { loader: loader, menu: menu(), toolbar: toolbar }; })(); $(function () { components .loader() .menu() .toolbar(); components .menu .open(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Comments
Post a Comment