Note:Observer mode, simple code
The main implementation code is as follows:
// A simple tool object that implements the basic elements required by the observer mode var publisher = {whatevertype: 'any', subscribers: {// 'any ': [] // when the subscription type is not specified, all messages are thrown into the default queue}. // subscribe to the event, type: event type, Handler: Event Processing Method Subscribe: function (type, Handler) {type = type | whatevertype; If (typeof this. subscribers [type] ==='undefined') {This. subscribers [type] = [];} This. subscribers [type]. push (handler) ;}, // stop the subscription event, type: event type, [handler]: event processing method (if not passed, the event subscription queue of type is cleared) unsu Bscribe: function (type, Handler) {type = type | whatevertype; var subscribers = This. subscribers [type] | []; for (VAR I = 0; I <subscribers. length; I ++) {If (! Handler | subscribers [I] === handler) {subscribers. splice (I, 1); I -- ;}}, // release event, type: event type, [Param]: Event parameter, format can be customized publish: function (type, Param) {type = type | whatevertype; var subscribers = This. subscribers [type] | []; for (VAR I = 0, Len = subscribers. length; I <Len; I ++) {subscribers [I] (PARAM );}}};
Next, write two objects at will.Publisher, One for doingSubscriber(I thought of the teacher's assignment to students ...)
// Tool function, copy the property of the source object to the target function extend (target, source) {for (var key in source) target [Key] = source [Key];} // kindly instructor var teacher ={}; extend (teacher, publisher); // obedient student var student = {dohomework: function () {console. log ('homework, I wanna die ');}, takeexam: function (PARAM) {console. log ('just '+ Param. week_left + 'weeks before final exams! Wtf ');}};
Simple test cases, not detailed:
Teacher.subscribe('homework', Student.doHomework);Teacher.subscribe('exam', Student.takeExam);Teacher.publish('homework'); //homework, i wanna die Teacher.publish('exam', {week_left: 2}); //just 2 weeks before final exams ! wtf Teacher.unsubscribe('homework', Student.doHomework);Teacher.publish('homework');Teacher.publish('exam', {week_left: 2}); //just 2 weeks before final exams ! wtf
The simple implementation of the observer mode, the code is simple, and the idea is not complicated. You can use the actual project with a slight modification as needed, communication and decoupling of project modules play a major role... N words omitted...