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


    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': '麻生希' }  );
    前端-语言
  • 相关阅读:
    解决margin 外边距合并问题
    tsx 校验 以及写法
    tsx 引入文件找不到
    Ubuntu 16.04安装和卸载软件命令
    Java8 中使用Stream 让List 转 Map使用总结
    Java8 Stream流式编程浅析
    浅析IOC 和 DI
    [ Java面试题 ]Java 开发岗面试知识点解析
    Intellij Idea 常用快捷键总结+实用小技巧
    Intellij Idea基础设置
  • 原文地址:https://www.cnblogs.com/beesky520/p/4491265.html
Copyright © 2020-2023  润新知