js中的观察者模式

解决了猪蹄对象喝观察者之间功能的耦合

var Observer = (function () {
        var _message = {};
        return {
            regist : function (type,fn) {
                if(typeof _message[type] === 'undefined'){
                    _message[type] = [fn];
                } else {
                    _message[type].push(fn);
                }
            },
            fire : function (type, args) {
                if(!_messgaes[type]){
                    return;
                }
                var envents = {
                    type, args: args|| {}
                }
                let i = 0;
                let len = _message[type].length;
                for(; i< len; i++){
                    _message[type][i].call(null, envents);
                }
            },
            remove : function (type, fn) {
                if(_message[type] instanceof Array){
                    var i = -_message[type].length - 1;
                    for(;i>0;i--){
                        _messgaes[type][i] === fn && _messgaes[type].splice(i,1)
                     }
                }
            },
        }
})();

你可能感兴趣的:(js中的观察者模式)