Skip to content

Instantly share code, notes, and snippets.

@slifin
Created April 3, 2015 23:31
Show Gist options
  • Save slifin/982d0464bbcb12975fb2 to your computer and use it in GitHub Desktop.
Save slifin/982d0464bbcb12975fb2 to your computer and use it in GitHub Desktop.
mediator pattern example using jquery
<!DOCTYPE html>
<html>
<head>
<title>Observer Pattern</title>
</head>
<body>
<div id="game-names"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script type="text/javascript">
(function(){
var o = $({});
$.each({
trigger:'publish',
on:'subscribe',
off:'unsubscribe',
one:'subscribeOnce'
}, function(key, val){
$[val] = function(){
o[key].apply(o,arguments);
};
});
})();
function Game(){
var that = {},
names = [],
setName = function(name){
names.push(name);
$.publish('game:name',name);
};
that.setName = setName;
return that;
}
$.subscribe('game:name',function(e,name){
console.log(e,name);
});
var game = Game();
game.setName('Team Fortress');
game.setName('Call of Duty');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment