Skip to content

Commit 50587a4

Browse files
committed
Add basic information about the module pattern
1 parent c4eb605 commit 50587a4

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

README.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -733,10 +733,65 @@ $scope.names = ['foo', 'bar', 'baz'];
733733

734734
will produce the same result as the one above. The main difference here is that the template is not wrapped inside a `script` tag but is HTML instead.
735735

736+
### Module Pattern
737+
738+
This is actually not a design pattern from Gang of Four, neither one from P of EAA. This is a tranditional JavaScript pattern, which main goal is to provide encapsulation and privacy.
739+
740+
Using the module pattern you can achieve privacy based on the JavaScript's functional lexical scope. Each module may have one or more private members, which are hidden in the local scope of a function, and an object, which exports the public API of the given module:
741+
742+
```javascript
743+
var Page = (function () {
744+
745+
var title;
746+
747+
function setTitle(t) {
748+
document.title = t;
749+
title = t;
750+
}
751+
752+
function getTitle() {
753+
return title;
754+
}
755+
756+
return {
757+
setTitle: setTitle,
758+
getTitle: getTitle
759+
};
760+
}());
761+
```
762+
763+
In the example above we have IIFE (Immediately-Invoked Function Expression), which after being called returns an object, with two methods (`setTitle` and `getTitle`). The returned object is being assigned to the `Page` variable.
764+
765+
In this case the user of the `Page` object does not has direct access to the `title` variable, which is defined inside the local scope of the IIFE.
766+
767+
The module pattern is very useful when defining services in AngularJS. Using this pattern we can simulate (and actually have) privacy:
768+
769+
```javascript
770+
app.factory('', function () {
771+
772+
function privateMember() {
773+
//body...
774+
}
775+
776+
function publicMember() {
777+
//body...
778+
privateMember();
779+
//body
780+
}
781+
782+
return {
783+
publicMember: publicMember
784+
};
785+
});
786+
```
787+
736788
## AngularJS application Patterns
737789

790+
### Prototype
791+
738792
### Data Mapper
739793

794+
740795
## References
741796

742797
1. [Wikipedia](https://en.wikipedia.org/wiki). The source of all brief descriptions of the design patterns is wikipedia.

0 commit comments

Comments
 (0)