I made an example for learning Dependency inversion principle in JavaScript OOP programming .
String.prototype.ucfirst = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
function textHandler(){
this.printRedbox = function( ){
return ' Red Box text ';
}
this.printBluebox = function( ){
return ' Blue Box text ';
}
};
function htmlHandler( handler ){
var block = [],
box = document.getElementById('container');
this.boxContentHandler = handler ;
this.setType = function( handler ){
this.boxContentHandler = handler
};
this.appendBlock = function( html ){
block.push( html );
box.innerHTML = block.join('');
};
this.printBox = function ( action ){
var title = this.printTitle() ,
text = this.boxContentHandler[ 'print'+ action.ucfirst() ](),
html = '<div class="box '+ action.replace('box','') +'">'
+ title + text
+'</div>' ;
this.appendBlock( html );
};
this.printTitle = function( ) {
return 'Title ' + block.length + ' <br />';
};
};
Here I am doing the action handling part
var htmlHandle = new htmlHandler( new textHandler() );
document.getElementById('bluebox').addEventListener( 'click', function(){
htmlHandle.printBox( this.id );
},false );
document.getElementById('redbox').addEventListener( 'click', function(){
htmlHandle.printBox( this.id );
},false );
I would like to know, is there a way to make it better. Did I miss anything here ?
htmlHandle
(rather than injected)? Why are you creating HTML from strings? Why are you joining strings for property lookup? You might want to read martinfowler.com/articles/injection.html \$\endgroup\$box.innerHTML = block.join('')
\$\endgroup\$JavaScript
. \$\endgroup\$