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
};
});
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。