js之模块通信

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
    };
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值