/ Published in: JavaScript
Expand |
Embed | Plain Text
// Module Pattern var Module = function() { _private1 = "private"; _history = []; function _privateReturner() { return _private1; } function _privateSender(set) { _history.push("From "+_private1+" to "+set); _private1 = set; } function _getHistory() { return _history; } return { publicReturner: _privateReturner, publicSender: _privateSender, publicHistory: _getHistory } }; /* var mod = new Module(); console.log(mod._private1); // undefined console.log(mod.publicReturner()); // private mod.publicSender("fishly"); mod.publicSender("fishly2"); mod.publicSender("bob"); mod.publicSender("kevin"); console.log(mod.publicReturner()); // fishly console.log(mod.publicHistory()); */ // Singleton Pattern var Singleton = (function() { var _private1 = 1; var _private2 = 2; var _total = 0; function _privateFunc() { _total = _private1 + _private2; } function getter() { return _total; } function setterReset(newVar) { _total = newVar; } return { getter: getter, setterReset: setterReset, publicVar: 1, changePrivate: function() { _privateFunc(); } } })(); /* Singleton.setterReset(0); console.log(Singleton.getter()); Singleton.changePrivate(); console.log(Singleton.getter()); */ // Observer pattern function Observer() { this.fns = []; } Observer.prototype = { subscribe: function(fn) { this.fns.push(fn); }, unsubscribe: function(fn) { this.fns = this.fns.filter( function(el) { if ( el !== fn ) { return el; } } ); }, fire: function(o, thisObj) { var scope = thisObj || window; this.fns.forEach( function(el) { el.call(scope, o); } ); } }; /* var o = new Observer; o.fire('here is my data'); var fn = function fn() { console.log('data data'); }; var fn3 = function fn3() { console.log('data data3 '); }; o.subscribe(fn); o.subscribe(fn3); o.unsubscribe(fn); o.fire('here is my data'); */
You need to login to post a comment.
