Multiple implementation version instances of the observer mode in the Javascript Design Mode

Source: Internet
Author: User

Multiple implementation version instances of the observer mode in the Javascript Design Mode

This article mainly introduces multiple implementation version instances of the observer mode of Javascript design mode. This article provides three implementation version codes and Jquery implementation versions. For more information, see

 

 

Introduction

The observer mode is also called the Publish/Subscribe mode. It defines a one-to-many relationship, allowing multiple observer objects to listen to a topic object at the same time, when the status of the topic object changes, all observer objects are notified so that they can automatically update themselves.

Benefits of using the observer mode:

1. supports Simple broadcast communication to automatically notify all subscribed objects.
2. After a page is loaded, the target object is easily dynamically associated with the observer, increasing flexibility.
3. the abstract coupling relationship between the target object and the observer can be expanded and reused separately.

Body (version 1)

In JS, the implementation of the observer mode is implemented through callback. We first define a pubsub object, which contains three methods: subscription, unsubscription, and release.

The Code is as follows:


Var pubsub = {};
(Function (q ){

Var topics ={}, // array stored by the callback function
SubUid =-1;
// Release Method
Q. publish = function (topic, args ){

If (! Topics [topic]) {
Return false;
}

SetTimeout (function (){
Var subscribers = topics [topic],
Len = subscribers? Subscribers. length: 0;

While (len --){
Subscribers [len]. func (topic, args );
}
}, 0 );

Return true;

};
// Subscription Method
Q. subscribe = function (topic, func ){

If (! Topics [topic]) {
Topics [topic] = [];
}

Var token = (++ subUid). toString ();
Topics [topic]. push ({
Token: token,
Func: func
});
Return token;
};
// Unsubscribe Method
Q. unsubscribe = function (token ){
For (var m in topics ){
If (topics [m]) {
For (var I = 0, j = topics [m]. length; I <j; I ++ ){
If (topics [m] [I]. token = token ){
Topics [m]. splice (I, 1 );
Return token;
}
}
}
}
Return false;
};
} (Pubsub ));

 

The usage is as follows:

 

The Code is as follows:


// Come, subscribe to
Pubsub. subscribe ('example1', function (topics, data ){
Console. log (topics + ":" + data );
});

// Release notification
Pubsub. publish ('example1', 'Hello world! ');
Pubsub. publish ('example1', ['test', 'A', 'B', 'C']);
Pubsub. publish ('example1', [{'color': 'blue'}, {'text': 'hello'}]);

 

How is it? Is it easy to use? However, there is a problem with this method, that is, there is no way to unsubscribe to the subscription. To unsubscribe to the subscription, you must specify the unsubscribe name. So let's use another version:

 

The Code is as follows:


// Assign the subscription value to a variable to unsubscribe.
Var testsubscribe = pubsub. subscribe ('example1', function (topics, data ){
Console. log (topics + ":" + data );
});

// Release notification
Pubsub. publish ('example1', 'Hello world! ');
Pubsub. publish ('example1', ['test', 'A', 'B', 'C']);
Pubsub. publish ('example1', [{'color': 'blue'}, {'text': 'hello'}]);

// Unsubscribe
SetTimeout (function (){
Pubsub. unsubscribe (testsubscribe );
}, 0 );

// Release it again to verify whether information can be output.
Pubsub. publish ('example1', 'Hello again! (This will fail )');

 

Version 2

We can also use the features of the prototype to implement an observer mode. The Code is as follows:

The Code is as follows:


Function Observer (){
This. fns = [];
}
Observer. prototype = {
Subscribe: function (fn ){
This. fns. push (fn );
},
Unsubscribe: function (fn ){
This. fns = this. fns. filter (
Function (el ){
If (el! = Fn ){
Return el;
}
}
);
},
Update: function (o, thisObj ){
Var scope = thisObj | window;
This. fns. forEach (
Function (el ){
El. call (scope, o );
}
);
}
};

// Test
Var o = new Observer;
Var f1 = function (data ){
Console. log ('robbin: '+ data +', hurry up! ');
};

Var f2 = function (data ){
Console. log ('randall: '+ data +', ask him to pay more! ');
};

O. subscribe (f1 );
O. subscribe (f2 );

O. update ("Tom is back! ")

// Unsubscribe f1
O. unsubscribe (f1 );
// Verify again
O. update ("Tom is back! ");

 

If you cannot find the filter or forEach function, it may be because your browser is not new enough and does not support the new standard function. You can define it as follows:

 

The Code is as follows:


If (! Array. prototype. forEach ){
Array. prototype. forEach = function (fn, thisObj ){
Var scope = thisObj | window;
For (var I = 0, j = this. length; I <j; ++ I ){
Fn. call (scope, this [I], I, this );
}
};
}
If (! Array. prototype. filter ){
Array. prototype. filter = function (fn, thisObj ){
Var scope = thisObj | window;
Var a = [];
For (var I = 0, j = this. length; I <j; ++ I ){
If (! Fn. call (scope, this [I], I, this )){
Continue;
}
A. push (this [I]);
}
Return;
};
}

 

Version 3

To enable multiple objects to have the observer publish and subscribe function, we can define a common function and apply the function to the object that requires the observer function. The Code is as follows:

 

The Code is as follows:


// Common Code
Var observer = {
// Subscribe
AddSubscriber: function (callback ){
This. subscribers [this. subscribers. length] = callback;
},
// Unsubscribe
RemoveSubscriber: function (callback ){
For (var I = 0; I <this. subscribers. length; I ++ ){
If (this. subscribers [I] === callback ){
Delete (this. subscribers [I]);
}
}
},
// Publish
Publish: function (what ){
For (var I = 0; I <this. subscribers. length; I ++ ){
If (typeof this. subscribers [I] === 'function '){
This. subscribers [I] (what );
}
}
},
// The object o has the observer function
Make: function (o ){
For (var I in this ){
O [I] = this [I];
O. subscribers = [];
}
}
};

 

Subscribe to the two objects blogger and user, and use the observer. make method to make the two objects have the observer function. The Code is as follows:

 

The Code is as follows:


Var blogger = {
Recommend: function (id ){
Var msg = 'dudu recommended post: '+ id;
This. publish (msg );
}
};

Var user = {
Vote: function (id ){
Var msg = 'Someone voted! ID = '+ id;
This. publish (msg );
}
};

Observer. make (blogger );
Observer. make (user );

 

It is easy to use. subscribe to different callback functions so that they can be registered to different observer objects (or multiple observer objects can be registered at the same time ):

 

Copy the Code as follows:


Var tom = {
Read: function (what ){
Console. log ('Tom sees the following information: '+ what)
}
};

Var mm = {
Show: function (what ){
Console. log ('Mm sees the following information: '+ what)
}
};
// Subscribe
Blogger. addSubscriber (tom. read );
Blogger. addSubscriber (mm. show );
Blogger. recommend (123); // call release

// Unsubscribe
Blogger. removeSubscriber (mm. show );
Blogger. recommend (456); // call release

// Subscription of another object
User. addSubscriber (mm. show );
User. vote (789); // call release

 

JQuery version

Based on the on/off function added in jQuery1.7, we can also define the observer of jQuery:

The Code is as follows:


(Function ($ ){

Var o =$ ({});

$. Subscribe = function (){
O. on. apply (o, arguments );
};

$. Unsubscribe = function (){
O. off. apply (o, arguments );
};

$. Publish = function (){
O. trigger. apply (o, arguments );
};

} (JQuery ));

 

The call method is simpler than the preceding three versions:

 

The Code is as follows:


// Callback function
Function handle (e, a, B, c ){
// 'E' is the event object and does not need to be followed.
Console. log (a + B + c );
};

// Subscribe
$. Subscribe ("/some/topic", handle );
// Publish
$. Publish ("/some/topic", ["a", "B", "c"]); // output abc


$. Unsubscribe ("/some/topic", handle); // unsubscribe

// Subscribe
$. Subscribe ("/some/topic", function (e, a, B, c ){
Console. log (a + B + c );
});

$. Publish ("/some/topic", ["a", "B", "c"]); // output abc

// Unsubscribe (the unsubscribe uses the/some/topic name instead of the callback function. It is different from the version 1 example.
$. Unsubscribe ("/some/topic ");

 

We can see that his subscription and Unsubscription use the string name instead of the callback function name, so even if the input is an anonymous function, we can unsubscribe it.

Summary

When an object needs to change other objects at the same time and does not know how many objects need to be changed, the observer mode should be considered.

In general, the work done by the observer mode is decoupling, so that both sides of the coupling depend on abstraction, rather than on specifics. So that their changes do not affect the changes on the other side.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.