Skip to content

Instantly share code, notes, and snippets.

@slifin
Last active August 29, 2015 14:18
Show Gist options
  • Save slifin/4d90596922d2ffca9831 to your computer and use it in GitHub Desktop.
Save slifin/4d90596922d2ffca9831 to your computer and use it in GitHub Desktop.
observer pattern example
<!DOCTYPE html>
<html>
<head>
<title>Observer Pattern</title>
</head>
<body>
<div id="game-names"></div>
<script type="text/javascript">
function Observable(){
var that = {},
listeners = [],
dispatch = function(eventName){
if (listeners[eventName]){
for(var i = 0; i < listeners[eventName].length;i++){
listeners[eventName][i](that);
}
}
},
on = function(eventName,listener){
if (!listeners[eventName])
listeners[eventName] = [];
listeners[eventName].push(listener);
},
off = function(eventName){
delete listeners[eventName];
}
that.dispatch = dispatch;
that.on = on;
that.off = off;
return that;
}
function GameModel(){
var that = Observable(),
names = [],
addName = function(name){
that.names.push(name);
that.dispatch('name-change');
},
removeName = function(){
that.names = [];
that.dispatch('name-change');
}
that.names = names;
that.addName = addName;
that.removeName = removeName;
return that;
}
function GameView(){
var that = {},
names = function(game){
document.getElementById('game-names')
.innerText = game.names.join(', ');
}
that.names = names;
return that;
}
(function GameController(){
var game = GameModel();
var view = GameView();
game.on('name-change',view.names);
game.addName('team fortress 2');
game.addName('call of duty');
game.addName('call of duty');
game.removeName();
game.addName('test');
game.off('name-change');
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment