0

What I've been trying to do is to pass a statement like oninput or onmouseover and then use them as actual statements in a method.

function Controller() {
  this.listen = function(elem, func, statement) {
    elem.statement = function() {//and then use it here
      func(elem);
    };
    return true;
  };
}

var age = document.getElementById('age');
var controller = new Controller();

controller.listen(age, callMe, oninput);//set the statement here

function callMe(elem) {
  console.log('hey');
}
<!DOCTYPE html>
<html>

<head>
  <title>HTML5, CSS3 and JavaScript demo</title>
</head>

<body>
  <input type="number" id="age" />
</body>

</html>

Is there a way to do this?

Kyle
  • 1,568
  • 2
  • 20
  • 46

1 Answers1

2

Pass the oninput as a string ("oninput") and then use square brackets to access the property of elem:

function Controller() {
  this.listen = function(elem, func, statement) {
    elem[statement] = function() {//and then use it here
      func(elem);
    };
    return true;
  };
}

var age = document.getElementById('age');
var controller = new Controller();

controller.listen(age, callMe, "oninput");//set the statement here

function callMe(elem) {
  console.log('hey');
}

However, I recommend you using element.addEventListener() instead of .onevent, see addEventListener vs onclick.

Community
  • 1
  • 1
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177