简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM