Last active
April 8, 2018 01:22
-
-
Save m-x-k/f63ed301288d195c90f5994c67b04c73 to your computer and use it in GitHub Desktop.
Javascript singleton pattern
This file contains hidden or 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
(function(win, $) { | |
var CircleGeneratorSingleton = (function() { | |
var instance; | |
function init() { | |
var _aCircle = [], | |
_stage = $('.advert'); | |
function _position(circle, left, top) { | |
circle.css('left', left); | |
circle.css('top', top); | |
} | |
function create(left, top) { | |
var circle = $('<div class=\"circle\"></div>'); | |
_position(circle, left, top); | |
return circle; | |
} | |
function add(circle) { | |
_stage.append(circle); | |
_aCircle.push(circle); | |
} | |
function index() { | |
return _aCircle.length; | |
} | |
return {index: index, | |
create: create, | |
add: add}; | |
} | |
return { | |
getInstance: function() { | |
if (!instance) { | |
instance = init(); | |
} | |
return instance; | |
} | |
} | |
})(); | |
$(win.document).ready(function() { | |
$('.advert').click(function(e) { | |
var cg = CircleGeneratorSingleton.getInstance(); | |
var circle = cg.create(e.pageX, e.pageY); | |
cg.add(circle); | |
}); | |
$(document).keypress(function(e) { | |
if (e.key == 'a') { | |
var cg = CircleGeneratorSingleton.getInstance(); | |
var circle = cg.create(Math.floor(Math.random()* 600), Math.floor(Math.random()* 600)); | |
cg.add(circle); | |
} | |
}); | |
}); | |
})(window, jQuery); |
This file contains hidden or 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> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="keywords" content="design patterns"> | |
<title>Mastering Javascript</title> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> | |
<style type="text/css" media="screen"> | |
.circle { | |
position: relative; | |
border-radius: 50%; | |
width: 50px; | |
height: 50px; | |
background-color: red; | |
} | |
</style> | |
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> | |
<script src="circleGeneratorSingleton.js"></script> | |
</head> | |
<body> | |
<h1>Circles</h1> | |
<h3>[Singleton Design Pattern]</h3> | |
<div class="container"> | |
<div class="advert"> | |
Press 'a' or click here to generate new circle. | |
</div> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment