The bridge mode of js design pattern

The bridge mode is mainly to decouple the implementation layer (events bound by elements) and the abstract layer (ui logic that decorates the page)
For example:
Pipe barefoot not afraid of level 1 message 5
First, we need to realize the hover effect when moving the mouse. Then we need to implement step by step:

function g(tag){
    return document.getElementByTagName(tag);
}
var spans=g('span');
spans[0].onmouseover=function(){
    this.style.color='red';
    this.background='#eedede';
    }
spans[0].onmouseout=function(){
    this.style.color='#dedede';
    this.style.background='red';
   }
spans[1].onmouseover=function(){
    this.document.getElenmentByTagName('strong')[0].style.color='#dedede';
    this.document.getElenmentByTagName('strong')[0]style.background='#ddd';
   }
spans[1].onmouseout=function(){
    this.document.getElenmentByTagName('strong')[0].style.color='#swswsw';
    this.document.getElenmentByTagName('strong')[0]style.background='red';
   }
   ......

The code is too redundant!!!! Now let's extract the common functions of the changed parts:

function changeColor(dom,color,bg){
    dom.style.color=color;
    dom.style.background=bg;
    }

Next, we pass the obtained this to the changecolor function through the anonymous callback function,

var spans = g(span);
spans[0].onmouseover=function(){
    changeColor(this,'red','#ddd')
    }
spans[0].onmouseout=function(){
    changeColor(this,'#ddd','red')
    }
spans[1].onmouseover=function(){
    changeColor(this.document.getElementByTagName('strong')[0],'red','#ddd')
    }
    ......

In addition, the strength of bridge mode is also very practical for diversified objects.
For example: in a simple game, people, balls, and sprites all have the same set of actions. The x, y coordinates change, and the colors of the balls and sprites are drawn in the same way.

//Multidimensional variable class
//Motion unit
function Speed(x,y){
    this.x=x;
    this.y=y;
    }
Speed.prototype.run=function(){......}
//Coloring unit
function Color(cl){
    this.color=cl;
    }
Color.prototype.draw=function(){......}
//Deformation unit
function Shape(sp){
    this.shape=sp;
    }
Shape.prototype.change=function(){......}
//Speaking unit
function Speak(wd){
    this.word=wd;
    }
Speak.prototype.say=function(){......}
//Create ball games
function Ball (x,y,c){
    this.speed=new Speed(x,y);
    this.color=new Color(c);
    }
 Ball.prototype.init=function(){
     this.speed.run();
     this.color.draw();
     }

//Create characters
function people(x,y,w){
    this.speed=new Speed(x,y);
    this.word=new Speak(w);
    }
People.prototype.init=function(){
    this.speed.run();
    this.word.say();
    }

//Instantiate character

var p = new People(10,20,'hahah');
p.init();


Posted by hhheng on Wed, 01 Apr 2020 05:41:08 -0700