3

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?

Community
  • 1
  • 1
hguser
  • 35,079
  • 54
  • 159
  • 293
  • Check my answer for more example: https://stackoverflow.com/questions/9226479/mediator-vs-observer-object-oriented-design-patterns/51350834#51350834 – Shahar Shokrani Jul 15 '18 at 18:05

1 Answers1

6

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.

sdabet
  • 18,360
  • 11
  • 89
  • 158
  • Sounds like a mix between both patterns: there is a central mediator entity but it stores observers in the targets instead of keeping the mapping in itself. – sdabet Sep 25 '13 at 09:42