Last active
September 1, 2017 16:11
-
-
Save paveltimofeev/c24b386b1a3f366aea44b77c3da80538 to your computer and use it in GitHub Desktop.
JS Patterns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Manager = function( action ){ | |
this._lock = false; | |
this._retry = 1; | |
this._action = action; | |
this._self = this | |
} | |
Manager.prototype.try = function (){ | |
this._retry++ | |
console.log(this._retry) | |
!this._lock && setTimeout( () => { | |
this._lock = this._retry; | |
this._action() | |
this._lock = false; | |
}, | |
1000 * this._retry ); | |
} | |
Manager.prototype.onSunccess = function(){ | |
this._lock = false; | |
this.retry = 0; | |
} | |
Manager.prototype.onFail = function(){ | |
this._lock = false; | |
this.try(); | |
} | |
var mgr = new Manager( () => { alert('xxx'); } ); | |
mgr.try() | |
mgr.onFail() | |
mgr.onFail() | |
mgr.onSunccess() | |
mgr.try() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Config = (function(){ | |
var instance; | |
function create(){ | |
return { | |
name: "Name", | |
print: function(){ return JSON.stringify(this); } | |
} | |
} | |
return { | |
getInstance: function(){ | |
if (!instance) | |
instance = create(); | |
return instance; | |
} | |
}; | |
})(); | |
/// USAGE /// | |
var ins1 = Config.getInstance(); | |
ins1.newProperty = "Prop was added after init but all instances have it." | |
var ins2 = Config.getInstance(); | |
ins2.name = "Peter" | |
/// OUTPUT /// | |
function write(data) { document.write( data+"<br>" ); } | |
write( JSON.stringify( ins1 ) ); // the same | |
write( JSON.stringify( ins2 ) ); // the same | |
write( ins1.print() ); | |
write( ins1.instance ); // undefined (private prop) | |
write( Config.instance ); // undefined (private prop) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment