Home > Web Front-end > JS Tutorial > Analyze the principles and functions of JavaScript observer pattern

Analyze the principles and functions of JavaScript observer pattern

零下一度
Release: 2017-04-19 11:08:58
Original
1858 people have browsed it

This article mainly introduces the principles and implementation methods of the JavaScript observer pattern (publish/subscribe), briefly analyzes the principles and functions of the JavaScript observer pattern, and gives the implementation skills of the observer pattern in the form of examples. The required Friends can refer to

The examples in this article describe the principles and implementation methods of the Javascript observer pattern (publish/subscribe). Share it with everyone for your reference, as follows:

The observer pattern is also called the publish-subscribe pattern. It defines a one-to-many relationship, allowing multiple observer objects to monitor a certain topic object at the same time. This All observing objects are notified when the subject object's state changes. It is composed of two types of objects, topics and observers. The topic is responsible for publishing events, and the observer observes the subject by subscribing to these events. The publisher and the subscriber are completely decoupled and do not know the existence of the other. Just share the name of a custom event.

In Nodejs, native support for this mode is implemented through EventEmitter. The event listening mechanism in Javascript can be understood as an observer pattern.

The following is a JS-customized PubSub. Reading the following code carefully will help you understand the observer pattern. Please check github for related code.


function PubSub() {
 this.handlers = {};
}
PubSub.prototype = {
  // 订阅事件
  on: function(eventType, handler){
    var self = this;
    if(!(eventType in self.handlers)) {
      self.handlers[eventType] = [];
    }
    self.handlers[eventType].push(handler);
    return this;
  },
   // 触发事件(发布事件)
  emit: function(eventType){
    var self = this;
    var handlerArgs = Array.prototype.slice.call(arguments,1);
    for(var i = 0; i < self.handlers[eventType].length; i++) {
     self.handlers[eventType][i].apply(self,handlerArgs);
    }
    return self;
  },
  // 删除订阅事件
  off: function(eventType, handler){
    var currentEvent = this.handlers[eventType];
    var len = 0;
    if (currentEvent) {
      len = currentEvent.length;
      for (var i = len - 1; i >= 0; i--){
        if (currentEvent[i] === handler){
          currentEvent.splice(i, 1);
        }
      }
    }
    return this;
  }
};
var pubsub = new PubSub();
var callback = function(data){
  console.log(data);
};
//订阅事件A
pubsub.on(&#39;A&#39;, function(data){
  console.log(1 + data);
});
pubsub.on(&#39;A&#39;, function(data){
  console.log(2 + data);
});
pubsub.on(&#39;A&#39;, callback);
//触发事件A
pubsub.emit(&#39;A&#39;, &#39;我是参数&#39;);
//删除事件A的订阅源callback
pubsub.off(&#39;A&#39;, callback);
pubsub.emit(&#39;A&#39;, &#39;我是第二次调用的参数&#39;);
Copy after login

Run results.

The above is the detailed content of Analyze the principles and functions of JavaScript observer pattern. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template