This article describes the principle and implementation method of the observer mode (publish subscription mode) of JavaScript design pattern. Share it for your reference, as follows:
Observer mode, also known as publish and subscription mode, defines a one-to-many relationship, allowing multiple observer objects to listen to a topic object at the same time. When the state of this topic object changes, all observer objects will be notified, so that they can automatically update their state.
In observer mode, it is not that an object calls another object's method, but that an object subscribes to another object's specific activity and gets notification after the state changes. Subscribers are also called observers, while the object being observed is called publishers or topics. When an important event occurs, the publisher will notify (invoke) all subscribers and may often pass messages in the form of event objects.
Ideas:
① The publisher needs an array type attributesubscribers, to store all subscribers;
② Subscribesubscribe()
: Add new subscribers to this array;
③ Unsubscribeunsubscribe()
: Delete a subscriber from the subscriber array;
④ Publishpublish()
: Circular traversalsubscribersEach element in the array and notify them, that is, sending a message means calling a method of the subscriber. Therefore, when a user subscribes to information, the subscriber needs tosubscribe()
Provide one of its methods.
subscribe()
、unsubscribe()
、publish()
All three methods require onetypeParameters, because the publisher may trigger multiple events, and the user may choose to subscribe to only one of them, not the other.
Benefits of using observer mode:
① Supports simple broadcast communication and automatically notifies all subscribed objects.
② After the page is loaded, the target object can easily have a dynamic relationship with the observer, which increases flexibility.
③ The abstract coupling relationship between the target object and the observer can be expanded and reused separately.
In JavaScript, event models are generally used to replace the traditional observer pattern. DOM events are also an observer pattern implemented between JavaScript and DOM.
Eg1:
Listen to the user's action of clicking a button, but there is no way to predict when the user will click. Therefore, the click event on the subscriber is posted to the subscriber when the button is clicked.
("click", function() { ("First click"); }, false); // There can be multiple subscribers("click", function() { ("Second click"); }, false); ();
Eg2:
Non-observer mode:
$.ajax({ url: './login', type: 'post', contentType: 'application/json', dataType:'json', success: function(data) { if( === "success") { // Login successfully, render header and footer (); (); } } });
Observer mode:
$.ajax({ ..., success: function(data) { if( === "success") { // Login successfully, post a successful login message ("loginsuccess", data); } } }); var header = (function() { // Listen to messages ("loginsuccess", function(data){ (); }); return { setInfo: function(data) { ("Rendering header"); } }; })(); var footer = (function() { ("loginsuccess", function(data){ (); }); return { setInfo: function(data) { ("Rendering nav"); } }; })();
For more information about JavaScript, please view the special topic of this site: "JavaScript object-oriented tutorial》、《Summary of JavaScript switching effects and techniques》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage》
I hope this article will be helpful to everyone's JavaScript programming.