Manipulating DOM inside custom function constructor

350 Views Asked by At

I wrote a function constructor with a prototype that is creating svg picture and inserting it into the web page. I have 2 questions though:

1 Is it all right to take part of the code inside of constructor that is being used in the process of creating instance and move it to the prototype object. As far as I see these prototype methods are used generally with already created instances, for example var a = [2,3,4]; a.reverse()

2 Is it fine to manipulate DOM-objects that way inside of function constructor? DOM objects are not js native objects, they are host objects outside of js-engine.They are similar to js objects but created by browser somewhere else

Below is the code:

function Sektor(selector, options) {
// Find a DOM object representing the HTML element with the supplied selector
// create a property called element
// This DOM object is assigned to the element property
  this.element = document.querySelector(selector);

// Some default values in case nothing is supplied
  const defaultOptions = {
    size: 100,
    circleColor: '#b3c9e0'
  };

// Merge options with default ones
  options = Object.assign(defaultOptions, options);
 
// Circle dimensions
  options.center = options.size / 2;
  options.radius = options.center;
  
// create a property called options
  this.options = options;

// Get SVG
  const svg = this.getCircle();

// SVG is injected into the DOM element with JavaScript
  this.element.innerHTML = svg;
}

// Assigning a method to the constructor's prototype
// This method generates SVG
Sektor.prototype.getCircle = function() {
  const options = this.options;
  return `
  <svg class='Sektor' viewBox='0 0 ${options.size} ${options.size}'> 
  <circle class='Sektor-circle' fill=${options.circleColor} cx='${options.center}' cy='${options.center}' r='${options.radius}' />
  </svg>
  `;
};


var sektor = new Sektor( '.example-one', { circleColor: '#7da385' } );
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>Draw</title>
 <style>
body {
 margin: 0;
 padding: 0;
}

.examples {
 display: flex;
 justify-content: space-between;
 padding: 20px;
}

.example {
 margin: 0px auto;
}

.Sektor {
 width: 200px;
 height: 200px;
 background-color:#f2f2f2;
}
 </style>
</head>
<body>
 <div class='examples'>
  <div class='example'>
   <div class='example-one'></div>
  </div>
 </div>  
 <script src='sektor.js'></script>
</body>
</html>

0

There are 0 best solutions below