js观察者模式

自己用TypeScript简单的实现了一个观察者模式,现在记录下来.

module observer {
    "use strict";
    var topics = {};

    /**
     * 订阅一个主题,请不要传入匿名函数,否则无法取消订阅
     * @param topic
     * @param callback
     */
    export function subscribe(topic:string, callback:()=>any) {
        if (!topics[topic]) {
            topics[topic] = [];
        }
        topics[topic].push(callback);
    }

    /**
     * 取消订阅一个主题,传入的函数为添加订阅时用到的那一个
     * @param topic
     * @param callback
     * @returns {boolean}
     */
    export function unSubscribe(topic:string, callback:()=>any) {
        var isDelete = false;
        if (!topics[topic]) {
            throw new Error('Unknown event string');
        }

        topics[topic].forEach(function (item:()=>any, index, array) {
            if (item === callback) {
                array.splice(index,1);
                isDelete = true;
            }
        });
        return isDelete;
    }

    export function publish(topic:string) {
        if (!topics[topic]) {
            throw new Error('Unknown event string');
        }
        topics[topic].forEach(function (item:()=>any, index, array) {
            setTimeout(function () {
                item();
            }, 0);
        });
    }
}
下面是生成的JS文件
var observer;
(function (observer) {
    "use strict";
    var topics = {};
    function subscribe(topic, callback) {
        if (!topics[topic]) {
            topics[topic] = [];
        }
        topics[topic].push(callback);
    }
    observer.subscribe = subscribe;
    function unSubscribe(topic, callback) {
        var isDelete = false;
        if (!topics[topic]) {
            throw new Error('Unknown event string');
        }
        topics[topic].forEach(function (item, index, array) {
            if (item === callback) {
                array.splice(index, 1);
                isDelete = true;
            }
        });
        return isDelete;
    }
    observer.unSubscribe = unSubscribe;
    function publish(topic) {
        if (!topics[topic]) {
            throw new Error('Unknown event string');
        }
        topics[topic].forEach(function (item, index, array) {
            setTimeout(function () {
                item();
            }, 0);
        });
    }
    observer.publish = publish;
})(observer || (observer = {}));


参考资料: http://www.cnblogs.com/TomXu/archive/2012/03/02/2355128.html

转载于:https://my.oschina.net/tcstory/blog/468799

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值