您的位置:首页 > Web前端 > JavaScript

使用js实现observer模式

2007-01-19 10:52 363 查看
在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);


                    }


                );


            }


        };        


        


        


        
d017
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>



 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  function javascript html yui
相关文章推荐