Singleton pattern

by John Wick

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<div class="advert">

</div>

CSS

.advert {
  background: white;
  border:1px solid red;
  width: 300px;
  height: 300px;
}

.circle{
  width:10px;
  height:10px;
  border-radius:50px;
  text-align:center;
  background:#000;
  position:absolute;
}

JavaScript

(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;
      }

      // using Revealing pattern
      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-5, e.pageY-5);
        cg.add(circle);
      });

      $(document).keypress(function(e) {
        if (e.key == 'a') {
          var cg = CircleGeneratorSingleton.getInstance();
          var circle = cg.create(Math.floor(Math.random()*400), Math.floor(Math.random()*400));
          cg.add(circle);
        }
      });

  });
})(window, jQuery);