Article From:

Today, there is a question about observer pattern:
Topic: there is an object a, and then there is an attribute props. When my props changes, B changes props output.
Then I think the code should be as follows:

var PubSub = (function() {  
    var eventObj = {};
    var props = 1;
    //SubscribeVar subscribe = function (event, FN) {Var props = arguments[0];If (PROps! = 1) {/ / / / / monitoring changesEventObj[event] = FN;}};/ / releaseVar pUblish = function (event) {If (eventObj[event]) {EventObj[event] ();}};Return {Subscribe: subscribe,Publish: publish}} ()));Var props2 = 2; / / if props2 = 1 here, it will not output.PubSub.subscribe (props2, function () {() {Console.log ('prOps is modified to'+props2);});PubSub.publish (props2);

In fact, the model of the observer is a little understood, but it is not yet very understood how to write in the form of code, do not know whether it is correct to write like this, ask the God to point out.

Answer 0:

I’m a Java developer myself, and the Observer pattern I’m using is also implemented in java. I’ll switch to JavaScript to implement it (see below).

function A(){
    this.observers = [];//Preserve the object of the observer}A.prototype.setProps = function (props) {This.props = props;/ / notifying observerFor (VAR i = 0; I < this.observers.length; i++) {This.observers[i].update (this, props);}};A.prototype.getProps = function (props) {Return this.props;};/ / add observerA.prototype.addObservEr = function (observer) {For (VaR I = 0; I < this.observers.length; i++) {If (this.observErs[i] = = = observer) / / / / already there is a direct returnReturn;}}This.observers.push (obserVer);};/ / removal of the observerA.prototype.removeObserver = function (observer) {For (VaR I = 0; I < this.obs)Ervers.length; i++) {If (this.observers[i] = = observer) {This.observers = this.observers.splice (I, 1);Return;}}};/ / observer 1Var B = {};B.update = funcTion (observerable, data) {Alert ("b->" +data);};/ / observer 2Var C = {};C.update = function (OBSErverable, data) {Alert ("c->" + data);};/ / the object to be observedVar a = new A ();/ / add observer BA.addObserver (B);/ / add observer CA.addObserver (c);/ / when the prop attribute changes, the update () method of the observer is automatically invoked.A.setProps ("HelloWorld");/ / / delete observerBA.removeObserver (b);A.setProps ("helloworld2");/ / this example can be written to optimize the way to use inheritance to achieve code reuse.

Answer 1:

The observer pattern (subscription release mode) should be that there can be a number of subscribers, the subscribers are not aware of each other, and the publisher doesn’t care how many people subscribe to it, and this is not reflected in your implementation.

Answer 2:

Recommended design mode observer mode: Uncle Tom blog

Answer 3:

The function of canceling the subscription

Leave a Reply

Your email address will not be published. Required fields are marked *