使用js实现observer模式

来源:互联网 发布:江歌的室友刘鑫 知乎 编辑:程序博客网 时间:2024/05/17 07:18
在yui中,大量使用customEvent。
何为customEvent,实际就是一个观察者observer。

下面给出这个observer的实现
<html>
    
<head>
        
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
        
<title>实现Observer模式.</title>
        
        
<script language=JavaScript>
        
function Observer() {
            
this.fns = [];
        }

        Observer.prototype 
= {
            subscribe : 
function(fn) {
                
this.fns.push(fn);
            }
,
            unsubscribe : 
function(fn) {
                
this.fns = this.fns.filter(
                    
function(el) {
                        
if ( el !== fn ) {
                            
return el;
                        }

                    }

                );
            }
,
            fire : 
function(o, thisObj) {
                
var scope = thisObj || window;
                
this.fns.forEach(
                    
function(el) {
                                    
//相当于:window.fn1(参数)  其中,参数是o.fire('xyz')中的xyz,转移成fn1和fn2执行了.
                        el.call(scope, o);
                    }

                );
            }

        }
;        
        
        
        
var o = new Observer;

        
var fn1 = function(p) {
            alert(
"fn1 " + p);
        }
;
        
var fn2 = function(p) {
            alert(
"fn2 " + p);
        }
;
        o.subscribe(fn1);
        o.subscribe(fn2);
        
        o.fire(
'xyz');
        
        
</script>

    
</head>
    
<body>
    
</body>
</html>