• JS 观察者模式


    Events = function() {

    var listen, log, obj, one, remove, trigger, __this;
    obj = {};
    __this = this;

    listen = function(key, eventfn) { //把简历扔盒子, key就是联系方式.
    var stack; //stack是盒子
    stack = obj[key] != null ? obj[key] : obj[key] = [];
    return stack.push(eventfn);
    };

    one = function(key, eventfn) {
    remove(key);
    return listen(key, eventfn);
    };

    remove = function(key) {
    return obj[key] != null ? obj[key].length = 0 : void (0);
    };

    trigger = function() { //面试官打电话通知面试者
    var fn, stack, i, len, key;
    key = Array.prototype.shift.call(arguments);
    stack = obj[key] != null ? obj[key] : obj[key] = [];
    for (i = 0, len = stack.length; fn=stack[i++];) {
    if (fn.apply(__this, arguments) === false) {
    return false;
    }
    }
    }
    return {
    listen: listen,
    one: one,
    remove: remove,
    trigger: trigger
    }


    }


    var adultTv = Events();

    adultTv.listen('play', function(data) {
    alert("whose file will show today " + data.name);
    });

    //发布者
    adultTv.trigger('play', {
    'name': 'david'
    })

  • 相关阅读:
    常见面试题
    3*0.1 == 0.3 将会返回什么?true 还是 false?
    poj_2186 强连通分支
    强连通分量、割点、桥
    最小生成树
    poj_2349 Kruskal 最小生成树
    poj_1258 prim最小生成树
    最短路径
    poj_1125 Floyd最短路
    poj_1860 SPFA
  • 原文地址:https://www.cnblogs.com/mguo/p/3148842.html
Copyright © 2020-2023  润新知