neitony
neitony

Reputation: 291

Passing object prototype function call into input keypress detection event handler

I am trying to pass an object prototype function call within an input keypress detection event handler but am not sure how to go about this. Any help would be greatly appreciated. The code is given below :

function foo{};

foo.prototype.shout = function() {
  alert(shout);
}

foo.prototype.someOtherFunction = function (event) {
  var e = event || window.event,
      code = e.charCode || e.keyCode;

    if(code === 38) {
       foo.shout// This is what doesn't work - sorry for the confusion
    }
}

foo.prototype.applyKeypress = function (_input) {
  var self = this;
      _input.onkeypress = foo.someOtherFunction; // someOtherFunction applied here
}

Upvotes: 1

Views: 1220

Answers (2)

ido
ido

Reputation: 811

As stated seconds before my post - you didn't create the object

http://jsfiddle.net/Smzuu/2/

I changed your code a little so it would run. Small things you missed out when writing this example code, I hope

function foo(){};

foo.prototype.shout = function() {
  alert("hello"); //alert(shout); // shout was not defined.
}

var sampleInput = document.getElementById('sampleInputField');

sampleInput.onkeypress = function(e) {
    if(e.charCode === 97) { // A pressed
      new foo().shout(); 
    }
}​

Upvotes: 2

zerkms
zerkms

Reputation: 254975

No, it doesn't work because you haven't created an object:

function foo(){};

foo.prototype.shout = function() {
  alert(shout);
}

var o = new foo();

var sampleInput = document.getElementById('sampleInputField');

sampleInput.onkeypress = function(e) {
  if(code === 38) { //up arrow press
    o.shout() //now it works because it's an object, not a constructor
  }
}

Upvotes: 1

Related Questions