Home  >  Article  >  Web Front-end  >  JavaScript observer pattern definition and detailed explanation of DOM event instances

JavaScript observer pattern definition and detailed explanation of DOM event instances

伊谢尔伦
伊谢尔伦Original
2017-07-24 14:33:031493browse

Observer pattern (publish-subscribe pattern): It defines a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it will be notified.

In JavaScript, the event model is generally used to replace the traditional observer pattern.
Benefits:

(1) It can be widely used in asynchronous programming and is an alternative to passing callback functions.

(2) It can replace the hard-coded notification mechanism between objects. One object no longer needs to explicitly call an interface of another object. The two objects are easily decoupled.

DOM Event – ​​Observer Pattern Example

We need to monitor the user’s click on document.body, but we have no way to predict when the user will click. .
So, we subscribe to the click event on document.body. When the body node is clicked, the body node publishes this message to the subscribers!


document.body.addEventListener("click", function() {
  console.log(1);
}, false);

// 可以多个订阅者
document.body.addEventListener("click", function() {
  console.log(2);
}, false);

doucment.body.click();

A certain website has header, nav navigation, message list and other modules. The rendering of these modules requires obtaining user login information.
(1) General writing method:


$.ajax({
  url: './login',
  type: 'post',
  contentType: 'application/json',
  dataType:'json',
  success: function(data) {
    if(data.status === "success") {
      // 登录成功,渲染header、nav
      header.setInfo(data.headerInfo);
      nav.setInfo(data.navInfo);
    }
  }
});

(2) Using the observer pattern, it is easy to decouple!


$.ajax({
  ...,
  success: function(data) {
    if(data.status === "success") {
      // 登录成功,发布登陆成功消息
      login.trigger("loginsuccess", data);
    }
  }
});

var header = (function() {
  // 监听消息
  login.listen("loginsuccess", function(data){
    header.setInfo(data.headerInfo);
  });
  return {
    setInfo: function(data) {
      console.log("设置header信息");
    }
  };
})();

var nav = (function() {
  login.listen("loginsuccess", function(data){
    nav.setInfo(data.navInfo);
  });
  return {
    setInfo: function(data) {
      console.log("设置nav信息");
    }
  }
})();

The above is the detailed content of JavaScript observer pattern definition and detailed explanation of DOM event instances. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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