Skip to content

Instantly share code, notes, and snippets.

@Janking
Created June 1, 2015 16:02
Show Gist options
  • Save Janking/3d15a5d37068758bbaf8 to your computer and use it in GitHub Desktop.
Save Janking/3d15a5d37068758bbaf8 to your computer and use it in GitHub Desktop.
pubsub模式-【典型版】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="count">点我</button>
<div id="show"></div>
<script type="text/javascript">
var Event = (function() {
var clientList = {},
listen,
trigger,
remove;
listen = function(key, fn) {
if (!clientList[key]) {
clientList[key] = [];
}
clientList[key].push(fn);
};
trigger = function(){
var key = Array.prototype.shift.call(arguments),
fns = clientList[key];
if(!fns || fns.length ===0){
return false;
}
for (var i = 0,fn; fn=fns[i++];) {
fn.apply(this,arguments);
}
};
remove = function(key,fn){
var fns = clientList[key];
if (!fns) {
return false;
}
if(!fn){
fns && (fns.length ===0);
}else{
for (var l = fns.length-1;l>=0; l--) {
var _fn = fns[l];
if(_fn === fn){
fns.splice(1,1);
}
}
}
};
return {
listen:listen,
trigger:trigger,
remove:remove
};
})();
var a = (function(){
var count = 0;
var button = document.getElementById('count');
button.onclick = function(){
Event.trigger('add',count++);
};
}());
var b = (function(){
var div =document.getElementById('show');
Event.listen('add',function(count){
div.innerHTML = count;
});
}());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment