definition:
In an event-driven environment, such as a browser that continues to seek user attention, the Observer pattern (aka Publisher-subscriber "Publisher-subscriber" mode) is a relationship between the manager and his or her task (specifically, the relationship between its object and its behavior and state).
) is a powerful tool. In JavaScript, the essence of this pattern is that you can observe the state of an object in the program and be notified when it changes.
Viewer API:
var publisher=function() {this. subscribers=[];} Push method Publisher.prototype.deliver=function(data) { this. Subscribers.foreach (function(FN) { fn (data); }) return This ; };
Subscription Method:
Function.prototype.subscribe=function(publisher) {varself= This; varAlreadyexists=publisher.subscribers.some (function(value) {returnValue = =Self ; } ); if(!alreadyexists) {Publisher.subscribers.push ( This); } return This ;};
Here's an episode where the translator adds the following code:
"Since any of the functions are instances of function, the new methods added in Function.prototype are inherited by all functions." Of course, adding subscribe to the Function.prototype is just for the sake of convenience and should not be done in the actual project. "
So what should I do? I couldn't help but ask.
var subscribe=function
var alreadyexists=publisher.subscribers.some (function (value) { return value ===self; } ); if (!alreadyexists) { Publisher.subscribers.push (this); }
(1)
function C (a) {alert (a+3)}
var publisher= new publisherSubscribe
. Call (A,publisher) (2)
Wow, that's all you can do. What a coincidence!!
Unsubscribe method:
function.prototype.unsubscribe=function(publisher) { var self=this; Publisher.subscribers=publisher.subscribers.filter (function(value) { return value!== self; } ); return This ; };
This, of course, can also be a form of the above function (1) (2):
var unsubscribe=function
publisher.subscribers= Publisher.subscribers.filter (function(value) { returnself ; } ) ; (3)function C (a) {alert (a+3)} varnew Publisher Unsubscribe.call (A,publisher) (4)
The OK observer pattern is roughly what it looks like ...
JavaScript design mode 15th Observer pattern-Learning notes