Created
June 1, 2015 16:02
-
-
Save Janking/3d15a5d37068758bbaf8 to your computer and use it in GitHub Desktop.
pubsub模式-【典型版】
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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