Realize
/* * js Observer pattern also known as subscribe/publish mode * by creating an observable object, you can advertise the event to * when an event of interest occurs All observers, thus forming loosely coupled */// Universal publisher Eventpublisher = base.extend ({publish: function (Data, type) {eventpublisher.publish (Data, type);}}, {subscribers : { any : [] // Event Type: subscribers }, // add a Subscriber-supplied calling method to an array of events for the subscribers subscription Subscribe : function (subscriber) { var type = subscriber.type | | ' Any '; if (typeof this.subscribers[type] = == ' undefined ') { this.subscribers[type] = []; } &nbsP; this.subscribers[type].push (subscriber.handleevent); }, // Delete subscribers unsubscribe : function (Fn, type) { this.visitsubscribers (' unsubscribe ', fn, type); }, // loops through each element in the subscribers and invokes the method they provide Publish : function (Publication, type) { This.visitsubscribers (' Publish ', publication, type); }, // helper visitSubscribers: function (Action, arg, type) { var pubtype = type | | ' Any ', subscribers = This.subscribers[pubtype], i, max = subscribers.length; for (i = 0; i < max; i += 1) { if (action === ' publish ') { // call Subscriber to subscribe to the method provided by this event subscribers[i] (ARG); } else { // find the method provided in the current subscription event and remove the if (Subscribers [I] === arg) { subscribers.splice (i, 1); } } } }});
Test
Implements the paper object, and all he does is publish the journal and monthly Paper = eventpublisher.extend ({ daily : function () { this.publish (' This is an important news ', ' Paper-daily '); }, monthly : function () { this.publish (' monthly survey ', ' paper-monthly '); } , Readweibo: function (Info) {console.log (' Significant news [' + info + '];}}); / Subscriber Object Joe, the object has 2 methods Person = eventpublisher.extend ({name: null,constructor: function ( Config) {this.name = config.name;}, drinkcoffee : function ( paper) { console.log (this.name + ' Start reading [' + paper + '] '); }, sundayprenap : function (monthly) { console.log (this.name + ' Start reading [' + monthly + ']; },weibo: function (msg) {this.publish (msg, ' Person-weibo ');}); Var paper = new paper (); Var darkness = new person ({name: ' Darkness '}); Eventpublisher.subscribe ({type: ' paper-monthly ', handleevent: function (data) { Darkness.sundayprenap (data);}}); Eventpublisher.subscribe ({type: ' paper-daily ', handleevent: function (data) {darkness.drinkcoffee (data);}); Eventpublisher.subscribe ({type: ' Person-weibo ', handleevent: function (data) {paper.readweibo ( (data);}); / paper started publishing the journal and monthly paper.daily ();p aper.monthly ()// darkness released Weibo information Darkness.weibo (' Today headline, 2015! ‘);
Reference
A JavaScript-inherited base class Base.js
JS Implementation Viewer mode (subscription/release mode)