js模块通信

实现功能

预览视频: http://7fvgk8.com1.z0.glb.clo...

模块加载器

使用require.js

目录结构

- index.html
- js
-  | ----lib
- ------  | ---- notify.js
- ------ app.js
- ------ greet.js
- ------ name.js

具体代码

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>module notify</title>
    <style type="text/css" media="screen">
        .wrapper  {
            width: 400px;
            height: 400px;
            margin: 40px auto;
            background: #f00;
            text-align: center;
            font-size: 14px;
            color: #fff;
        }
        button {
            outline: none;
            margin-top: 40px;
        }
        .greet {
            color: #0f0;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <button id="notify" type="button">start to notify</button>
        <div id="greet"></div>
    </div>
    <script data-main="js/app" src="http://cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
</body>
</html>

js/app.js

define(['greet'], function (greet) {
    greet.init();
});

js/greet.js

define(['lib/notify', 'name'], function (notify, name) {
    function init () {
        var content = 'hello ';
        var notifyEle = document.getElementById('notify');
        var greetEle = document.getElementById('greet');

        name.receive();
        notifyEle.addEventListener('click', function () {
            notify.send(['greet'], 'getName', {ele: greetEle, preStr: (content + ' ')});
        }, false);
    }

    return {
        init: init
    }
});

js/name.js

define(['lib/notify'], function (notify) {
    function receive () {
        notify.receive(['greet'], 'getName', function (data) {
            data.ele.innerHTML = data.preStr + 'mumu';
        });
    }
    return {
        receive: receive
    }
});

js/lib/notify.js

define(function () {
    var g = window;
    g.notifyReceiverPool = g.notifyReceiverPool || {};

    function send (modules, event, data) {
        modules.forEach(function (module) {
            g.notifyReceiverPool[module][event].callback && g.notifyReceiverPool[module][event].callback(data);
        });
    }

    function receive (modules, event, callback) {
        if (!callback) {
            return;
        }

        modules.forEach(function (module) {
            g.notifyReceiverPool[module] = g.notifyReceiverPool[module] || {};
            g.notifyReceiverPool[module][event] = g.notifyReceiverPool[module][event] || {};
            g.notifyReceiverPool[module][event].callback = callback;
        });
    }

    return {
        send: send,
        receive: receive
    };
});

luckyyulin
217 声望9 粉丝

有一种鸟没有脚,他的一生只能在天上飞来飞去,飞累了就在风里睡觉,一辈子只能落地一次,那就是他死的时候