How to create a Constructor when there is if/Else and external variables?

Asked

Viewed 105 times

-2

I have several variables like this, that call an HTML element always with the same name:

var $inputFromA = $(".inputFromA");

It’s at least 10: inputFromA, inputFromB, inputFromC

All these variables also call exactly the same function:

$inputFromA.on("input", function () {
  var val = $(this).prop("value");
  if (val < min) {
    val = min;
  } else if (val > to) {
    val = to;
  }
  instance.update({
    from: val
  });
});

It is possible to create a constructor function or constant class so that I can only declare the variable name and call only the class/function?

I imagine it would be something like:

class InputFrom () {}

var inputFromA = new InputFrom;

My difficulty is due to the amount of parameters that such a function should have. Someone could give me a strength with this?

  • 1

    What is this instance in the code? Why do you want to create the class? Your question is not clear; it would be good for you to [Edit] to make it a little clearer.

  • I am working with Ion.Rangeslider (http://ionden.com/a/plugins/ion.rangeSlider/index.html) and instance is required for the slider to fill a input with a number.

1 answer

1


You can relate this function to a constant or a variable, and then return the result of this function:

let ChamaFuncao = $inputFromA.on("input", function () {
  var val = $(this).prop("value");
  if (val < min) {
    val = min;
  } else if (val > to) {
    val = to;
  }
  instance.update({
    from: val
  });
return ChamaFuncao;
});

after here just call the function whenever you want to use it.

here is a link explaining well about Return: https://www.w3schools.com/Jsref/jsref_return.asp

  • 2

    Excellent your solution, Vitor!! Thank you very much, friend! I just edited your answer so that the code is better to be viewed. Brigadão!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.