how to implement observer pattern in javascript?

前端 未结 9 1574
执笔经年
执笔经年 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条回答
  •  梦如初夏
    2021-01-30 08:04

    Below is an implementation i adapted a little from the book Learning Javascript Design Patterns.

    function pubsub(obj) {
    
    var events = {},
        subUid = -1;
    
    obj.publish = function (event, args) {
    
        if (!events[event]) {
            return false;
        }
    
        var subscribers = events[event],
        len = subscribers ? subscribers.length : 0;
    
        while (len--) {
            subscribers[len].func(event, args);
        }
    };
    
    obj.subscribe = function (event, func) {
    
        if (!events[event]) {
            events[event] = [];
        }
    
        var token = (++subUid).toString();
        events[event].push({
            token: token,
            func: func
        });
    
        return token;
    
    };
    
    obj.unsubscribe = function (token) {
    
        for (var event in events) {
            if (events.hasOwnProperty(event)) {
                for (var i = 0, j = events[event].length ; i < j ; i++) {
                    if (events[event][i].token === token) {
                        events[event].splice(i, 1);
                    }
                }
            }
        }
    
        return this;
    
    };
    
    }
    
    var obj = {}; // Any javascript object
    pubsub(obj); // Make an observable from the given object
    
    var subscription = obj.subscribe('load', handler);
    
    // event handler callback
    function handler(event, data) {
        console.log(event, data);
    }
    
    obj.publish('load', 'Data loaded successfully'); // logs 'load Data loaded successfully'
    obj.unsubscribe(subscription);
    obj.publish('load', 'Data loaded successfully'); // nothing happens
    

    Cheers!

提交回复
热议问题