码迷,mamicode.com
首页 > 编程语言 > 详细

201505092150_《Javascript模式-观察者模式》

时间:2015-05-09 23:24:57      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

1.  定义

Events = function() {
 
           var listen, log, obj, one, remove, trigger, __this;
 
           obj = {};
 
           __this = this;
 
           listen = function( key, eventfn ) {  //把简历扔盒子, key就是联系方式.
 
             var stack, _ref;  //stack是盒子
 
             stack = ( _ref = obj[key] ) != null ? _ref : obj[ key ] = [];
 
             return stack.push( eventfn );
 
           };
 
           one = function( key, eventfn ) {
 
             remove( key );
 
             return listen( key, eventfn );
 
           };
 
           remove = function( key ) {
 
             var _ref;
 
             return ( _ref = obj[key] ) != null ? _ref.length = 0 : void 0;
 
           };
 
           trigger = function() {  //面试官打电话通知面试者
 
             var fn, stack, _i, _len, _ref, key;
 
             key = Array.prototype.shift.call( arguments );
 
             stack = ( _ref = obj[ key ] ) != null ? _ref : obj[ key ] = [];
 
             for ( _i = 0, _len = stack.length; _i < _len; _i++ ) {
 
               fn = stack[ _i ];
 
               if ( fn.apply( __this,  arguments ) === false) {
 
                 return false;
 
               }
 
             }
 
             return {
 
                listen: listen,
 
                one: one,
 
                remove: remove,
 
                trigger: trigger
 
             }
 
           }
 
2.使用
 
    
var adultTv = Event();
 
adultTv .listen(  ‘‘play‘,  function( data ){
 
   alert ( "今天是谁的电影" + data.name );
 
});
 
//发布者
 
adultTv .trigger(  ‘‘play‘,  { ‘name‘: ‘麻生希‘ }  );

201505092150_《Javascript模式-观察者模式》

标签:

原文地址:http://www.cnblogs.com/beesky520/p/4491265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!