Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript mediator vs observer

First I want to say I have googled javascript mediator vs observer and read almost ten links.

Also I search in statckoverflow and I got this Mediator Vs Observer Object-Oriented Design Patterns and mediator-vs-observer.

However I still do not have clear understand about the difference between them.

So I wonder if someone can explain them more clearly?

Maybe a live example. :)

Thanks.


I tried to create an example, is this a pattern of mediator?

code:

var EventMediator = {
    publish: function (target, message) {
        var args = Array.prototype.slice.call(arguments, 2);
        var msgs = target.messages || [];
        for (var i = 0; i < msgs.length; i++) {
            var msg = msgs[i];
            msg.callback.apply(msg.context, args);
        }
    },
    register: function (target, message, fn) {
        target.messages = target.messages || [];
        target.messages.push({
            context: target,
            callback: fn
        });
    }
};

var t1 = {name: 'kk'};
var t2 = {name: 'gg'};

EventMediator.register(t1, "nameChanged", function () {
    console.info("t1 name chagned");
});
EventMediator.publish(t1, "nameChanged");

Here I want to know if the Mediator should know about the exist of the object who trigger the message?

like image 852
hguser Avatar asked Aug 09 '26 04:08

hguser


1 Answers

Observer pattern: the observed object manages its own list of observers (aka listeners) which must be notified when a certain event happens.

Mediator pattern: the observed object is not aware of the list of its observers, there is an external entity that makes the mapping between observed objects and observers.

like image 169
sdabet Avatar answered Aug 11 '26 09:08

sdabet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!