how to implement observer pattern in javascript?

前端 未结 9 1586
执笔经年
执笔经年 2021-01-30 07:29

Hi I\'m tyring to implement observer pattern in JavaScript:

My index.js:

$(document).ready(function () {
  var ironMan = new Movie();
           


        
9条回答
  •  旧时难觅i
    2021-01-30 08:13

    For me this is the best way to implement an Observer pattern in JS

    function Click() {
        this.handlers = [];  // observers
    }
    
    Click.prototype = {
    
        subscribe: function(fn) {
            this.handlers.push(fn);
        },
    
        unsubscribe: function(fn) {
            this.handlers = this.handlers.filter(
                function(item) {
                    if (item !== fn) {
                        return item;
                    }
                }
            );
        },
    
        fire: function(o, thisObj) {
            var scope = thisObj || window;
            this.handlers.forEach(function(item) {
                item.call(scope, o);
            });
        }
    }
    
    // log helper
    
    var log = (function() {
        var log = "";
    
        return {
            add: function(msg) { log += msg + "\n"; },
            show: function() { alert(log); log = ""; }
        }
    })();
    
    function run() {
    
        var clickHandler = function(item) { 
            log.add("fired: " + item); 
        };
    
        var click = new Click();
    
        click.subscribe(clickHandler);
        click.fire('event #1');
        click.unsubscribe(clickHandler);
        click.fire('event #2');
        click.subscribe(clickHandler);
        click.fire('event #3');
    
        log.show();
    }
    

提交回复
热议问题