Home > Web Front-end > JS Tutorial > body text

Observer pattern in Javascript

php中世界最好的语言
Release: 2018-03-13 17:51:53
Original
1448 people have browsed it

This time I will bring you Observer Pattern of Javascript, what are the precautions of Javascript Observer Pattern, the following is a practical case, let’s take a look take a look.

The observer (also known as publish-subscribe) pattern defines a one-to-many dependency relationship between objects, so that when the state of an object changes, all objects that depend on it are notified and automatically refreshed. .

When the user performs some operations on the web page (such as clicking), he needs to perform some predetermined events (such as form submission, jump page)

Advantages: Between publisher and subscription Reduced coupling between objects

Disadvantages: Weakening the relationship between objects, which is not conducive to the maintenance and understanding of the code

Implementation ideas

Determine the publisher

Define publisher cache list, store Callback functionNotify subscribers

Publish messages and execute cache list callback function in sequence

Simple implementation

let event = {};
event.list = [];//增加订阅者event.listen = function(fn){
    event.list.push(fn);
}//发布消息event.trigger = function(){    for(var i = 0,fn; fn = this.list[i++];) {
        fn.apply(this,arguments); 
    }
}let click = function(){    console.log('event:click');
}let hover = function(){    console.log('event:hover');
}
event.listen(click);
event.listen(hover);
event.trigger();//打印:‘event:click’'event:hover'
Copy after login

Perfect observer Mode

let Event = (function(){    var list = {},
        listen,
        trigger,
        remove;
    listen = function(key,fn){        list[key] = list[key]||[];        list[key].push(fn);
    };
    trigger = function(){        var key = Array.prototype.shift.call(arguments),
            fns = list[key];        if(!fns || fns.length === 0) {            return false;
        }        for(var i = 0, fn; fn = fns[i++];) {
            fn.apply(this,arguments);
        }
    };
    remove = function(key,fn){        var fns = list[key];        if(!fns) {            return false;
        }        if(!fn) {
            fns && (fns.length = 0);
        }else {            for(var i = fns.length - 1; i >= 0; i--){                var _fn = fns[i];                if(_fn === fn) {
                    fns.splice(i,1);
                }
            }
        }
    };    return {
        listen: listen,
        trigger: trigger,
        remove: remove
    }
})();
Event.listen('click', function(type) {
    console.log('event: ' + type +' click'); 
});
Event.trigger('click' , 'button');//打印'event: button click'
Copy after login

The observer mode can be used for inter-module communication, subscribing to user events and status, and triggering the execution of corresponding logical processing.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Javascript’s proxy mode

Javascript’s strategy mode

The above is the detailed content of Observer pattern in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template