Improved javascript in Dat.GUI

6

Hello.

I created a simple block, using CSS variables .

And to "set" these variables to test criteria, I'm using Dat.GUI . The current code is on this Pen .

My question is how to improve this code, but specifically on lines 33-50 (the latter) there is a code repetition forced by me because it seems necessary to play on a variable to use the onChange callback.

var config = function() {
  this.title = 'Lorem ipsum dolor sit amet, consect etur adipisicing elit.';
  this.photo = true;
  this.avatar = true;
  this.avatarAlign = 'left';
  this.cardRadius = 20;
  this.avatarSize = 75;
  this.avatarRadius = 10;
  this.mainColor = '#1abc9c';
  this.paddingSide = 20;
  this.paddingMiddle = 15;
};

function changeCSS(){
  console.log('teste');
}

window.onload = function() {
  var block = new config();
  var gui = new dat.GUI();
  gui.add(block, 'title');
  gui.add(block, 'photo');
  gui.add(block, 'avatar');
  gui.add(block, 'avatarAlign', ['left', 'center', 'right']);
  var cssVars = gui.addFolder('CSS Variables');
  var mainColor     = cssVars.addColor(block, 'mainColor');
  var cardRadius    = cssVars.add(block, 'cardRadius').min(0).step(1).max(10);  
  var avatarSize    = cssVars.add(block, 'avatarSize').min(40).step(5).max(120);  
  var avatarRadius  = cssVars.add(block, 'avatarRadius').min(0).step(1).max(10);  
  var paddingSide   = cssVars.add(block, 'paddingSide').min(0).step(1).max(60);  
  var paddingMiddle = cssVars.add(block, 'paddingMiddle').min(0).step(1).max(60);
  
mainColor.onChange(function(value) {
  changeCSS();
});
cardRadius.onChange(function(value) {
  changeCSS();
});
avatarSize.onChange(function(value) {
  changeCSS();
});
avatarRadius.onChange(function(value) {
  changeCSS();
});
paddingSide.onChange(function(value) {
  changeCSS();
});
paddingMiddle.onChange(function(value) {
  changeCSS();
});
  
};

What would be the correct way to call a function, whatever the changed attribute?

    
asked by anonymous 13.06.2017 / 18:26

1 answer

0

For this you must create an object:

var dry = [];

And instead of creating a variable for each item, add them to the object:

dry.push(
  cssVars.addColor(block, 'mainColor'),
  cssVars.add(block, 'cardRadius').min(0).step(1).max(10),
  cssVars.add(block, 'avatarSize').min(40).step(5).max(120),
  cssVars.add(block, 'avatarRadius').min(0).step(1).max(10),
  cssVars.add(block, 'paddingSide').min(0).step(1).max(60),
  cssVars.add(block, 'paddingMiddle').min(0).step(1).max(60)
);

Then loop to apply the callback:

for (var i = 0; i < dry.length; i++) {
  dry[i].onChange(function (value) {
    changeCSS(value);
  });
}
  

You can see it working at stackblitz

    
28.03.2018 / 14:07