Home Web Front-end JS Tutorial Multiple implementation examples of Javascript design pattern Observer pattern_javascript skills

Multiple implementation examples of Javascript design pattern Observer pattern_javascript skills

May 16, 2016 pm 04:11 PM
javascript Observer pattern Design Patterns

Introduction

The observer mode is also called the publish/subscribe mode (Publish/Subscribe). It defines a one-to-many relationship, allowing multiple observer objects to monitor a certain topic object at the same time. When the status of the topic object changes, All observer objects will be notified so that they can update themselves automatically.

Benefits of using the observer pattern:

1. Support simple broadcast communication and automatically notify all subscribed objects.
2. After the page is loaded, the target object can easily have a dynamic relationship with the observer, which increases flexibility.
3. The abstract coupling relationship between the target object and the observer can be independently extended and reused.

Text (version 1)

The implementation of the observer pattern in JS is achieved through callbacks. Let's first define a pubsub object, which contains 3 methods: subscribe, unsubscribe, and publish.

Copy code The code is as follows:

var pubsub = {};
(function (q) {

var topics = {}, // Array stored in callback function
        subUid = -1;
//Publish 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;
};
//How to unsubscribe
​ 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));

Use as follows:

Copy code The code is as follows:

//Come and subscribe
pubsub.subscribe('example1', function (topics, data) {
console.log(topics ": " data);
});

//Publish notification
pubsub.publish('example1', 'hello world!');
pubsub.publish('example1', ['test', 'a', 'b', 'c']);
pubsub.publish('example1', [{ 'color': 'blue' }, { 'text': 'hello'}]);

How about it? Isn’t it great to use? But there is a problem with this method, that is, there is no way to unsubscribe. If you want to unsubscribe, you must specify the name of the unsubscription, so let’s come up with another version:

Copy code The code is as follows:

//Assign the subscription to a variable to unsubscribe
var testSubscription = pubsub.subscribe('example1', function (topics, data) {
console.log(topics ": " data);
});

//Publish 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(testSubscription);
}, 0);

//Publish again to verify whether the information can still be output
pubsub.publish('example1', 'hello again! (this will fail)');

Version 2

We can also use the characteristics of prototypes to implement an observer pattern. The code is as follows:

Copy code 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) {
                                                                                                                                                                                                                                                                                   }                                                                                                        } );
},
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 ', get to work quickly!');
};

var f2 = function (data) {
console.log('Randall: ' data ', ask him to increase his salary!');
};

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 are prompted that the filter or forEach function cannot be found, it may be because your browser is not new enough and currently does not support the new standard functions. You can define it yourself using the following method:

Copy code 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 a;
};
}

Version 3

If we want multiple objects to have the observer publish and subscribe function, we can define a general function, and then apply the function of this function to the objects that need the observer function. The code is as follows:

Copy code The code is as follows:

//General 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);
            }
}
},
// Make object o have observer function
Make: function (o) {
for (var i in this) {
            o[i] = this[i];
               o.subscribers = [];
}
}
};

Then subscribe to two objects blogger and user, and use the observer.make method to make these two objects have observer functions. The code is as follows:

Copy code The code is as follows:

var blogger = {
Recommend: function (id) {
        var msg = 'Posts recommended by dudu:' id;
This.publish(msg);
}
};

var user = {
vote: function (id) {
        var msg = 'Someone voted! ID=' id;
This.publish(msg);
}
};

observer.make(blogger);
observer.make(user);

The usage method is relatively simple. Subscribe to different callback functions so that you can register to different observer objects (you can also register to multiple observer objects at the same time):

Copy code The code is as follows:

var tom = {
Read: function (what) {
console.log('Tom saw the following message: ' what)
}
};

var mm = {
show: function (what) {
console.log('mm saw the following information: ' what)
}
};
// Subscribe
blogger.addSubscriber(tom.read);
blogger.addSubscriber(mm.show);
blogger.recommend(123); //Call to publish

//Unsubscribe
blogger.removeSubscriber(mm.show);
blogger.recommend(456); //Call to publish

//Subscription of another object
user.addSubscriber(mm.show);
user.vote(789); //Call publish

jQuery version

According to the new on/off function of jQuery version 1.7, we can also define jQuery version of observers:

Copy code 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 calling method is simpler than the above three versions:

Copy code The code is as follows:

//Callback function
function handle(e, a, b, c) {
// `e` is an event object, no need to pay attention
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 (unsubscribe uses the /some/topic name instead of the callback function, which is different from the example in version 1
$.unsubscribe("/some/topic");

As you can see, his subscription and unsubscription use string names instead of callback function names, so even if an anonymous function is passed in, we can still unsubscribe.

Summary

The use case of observers is: when changes to one object require changes to other objects at the same time, and it does not know how many objects need to be changed, you should consider using the observer pattern.

In general, what the observer pattern does is decoupling, making both parties of the coupling rely on abstraction rather than concreteness. So that changes on each side will not affect changes on the other side.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between design patterns and architectural patterns in Java framework The difference between design patterns and architectural patterns in Java framework Jun 02, 2024 pm 12:59 PM

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

Analysis of the Decorator Pattern in Java Design Patterns Analysis of the Decorator Pattern in Java Design Patterns May 09, 2024 pm 03:12 PM

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

PHP design pattern practical case analysis PHP design pattern practical case analysis May 08, 2024 am 08:09 AM

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

How design patterns deal with code maintenance challenges How design patterns deal with code maintenance challenges May 09, 2024 pm 12:45 PM

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

The wonderful use of the adapter pattern in Java design patterns The wonderful use of the adapter pattern in Java design patterns May 09, 2024 pm 12:54 PM

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

PHP Design Patterns: Test Driven Development in Practice PHP Design Patterns: Test Driven Development in Practice Jun 03, 2024 pm 02:14 PM

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

Application of design patterns in Guice framework Application of design patterns in Guice framework Jun 02, 2024 pm 10:49 PM

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

What are the advantages and disadvantages of using design patterns in java framework? What are the advantages and disadvantages of using design patterns in java framework? Jun 01, 2024 pm 02:13 PM

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

See all articles