-Make code written with maintainability, reusability, portability. Instead of focusing on the code itself, think of the code from a macro perspective, how to plan and manage the code
-The code satisfies at least " low-coupling high cohesion "
- Low coupling : The code between each module is not relevant
- High cohesion : Each module code is made up of highly correlated code that is used to achieve a single function, with the principle of a single responsibility
< Span class= "token lf" > -How to perform separate functions where they need to be performed- > Subscription Publishing mode
< Span class= "token lf" > subscription : plan
< Span class= "token MD md-li" > release : execution plan
Fetch subscription : cancel schedule
function fn1 () {} function fn2 () {}document.addeventlistener(' Click ', Fn1,false);d ocument.addeventlistener (' Click ', fn2,false);d ocument.removeeventlistener (' click ', fn2,false);
When the mouse clicks this thing to happen:
Make a plan: the behavior of adding bindings to events FN1,FN2
Cancel schedule: The behavior of unbinding an event fn2
Execution plan: When the user clicks
Basic exercises for subscribing to the release pattern:
<!doctype html>//make a plan on //Cancel Schedule off //Execution Plan fireLet Odiv = document.getElementById (' Div1 '); functionfn1 () {alert (' First method '); } functionfn2 () {alert (' Second method '); } functionFn3 () {alert (' Third method '); } on (Odiv,' Marry ', FN1); On (Odiv,' Marry ', FN2); On (Odiv,' Marry ', FN3); Off (Odiv,' Marry ', FN3); Window.settimeout (function() {Fire.call (Odiv,' Marry '); },1000); functionOn (ELE,TYPE,FN) {//there's an event pool, with events-related behavior. //How to define event pools (arrays) that are related to event types ele[' my ' +type] + ' my ' to differentiate from system events if(!ele[' my ' +Type]) {ele[' My ' + type] = []; } Let a= Ele[' my ' +type]; A.foreach (function(Item,index) {//Handling Duplicate Bindings if(item = = FN)return; }) A.push (FN);//Put each behavior in the event-related event pool } functionoff (ELE,TYPE,FN) {//1. Get the event poolLet a = ele[' my ' +type]; //traverse the event pool to see if there is a plan if(a && a.length > 0) {A.foreach (function(item, index) {if(item = = =fn) { //prevent an array from collapsing, false removalA[index] =NULL; } })}//For (Let i = 0; i < a.length; i++) {//if (a[i] = = = fn) {//a[i] = null;// }// }// } } functionFire (type) {//release plan cancels the plan in the event poolLet A = This[' My ' +type]; if(a && a.length > 0){ for(Let i = 0; i < a.length; i++){ if(typeofA[i] = = = ' function ') {A[i].call ( This); }Else{A.splice (i,1); I--; } } } }</script>
Subscription Publishing Model conceptual basis