Skip to content

Instantly share code, notes, and snippets.

@paveltimofeev
Last active September 1, 2017 16:11
Show Gist options
  • Save paveltimofeev/c24b386b1a3f366aea44b77c3da80538 to your computer and use it in GitHub Desktop.
Save paveltimofeev/c24b386b1a3f366aea44b77c3da80538 to your computer and use it in GitHub Desktop.
JS Patterns
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()
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