1

I have a simple event listener but need to parse this through it to my function but don't know how.

This is what i have so far:

var inpt = document.getElementById('curq');
inpt.addEventListener("keyup", function(e,max){ int_inpt_only(e,max); } , false);

function int_inpt_only(e,max) {
                this.value = this.value.replace(/[^0-9]/g,'');
                if(this.value > max) this.value = max;
                if(this.value<1)this.value=1;
}

The problem is this is not defined in my function because the scope does not carry through, so i am wondering how i link them without having to look up the element two times.

Sir
  • 7,735
  • 12
  • 72
  • 138

2 Answers2

2

Using Function.call:

inpt.addEventListener("keyup", function (e) {
    int_inpt_only.call(this, e, 100);
}, false);

Demo


There was also a small quirk with your posted handler logic:

inpt.addEventListener("keyup", function(e,max){ int_inpt_only(e,max); } , false);
                                          ^^^

Event handlers don't receive a second argument so max is undefined there.


Or, if that is all your event handler does and the int_inpt_only can access the max variable through lexical scope (e.g. defined in an outer scope), just pass a function reference as event handler instead:

inpt.addEventListener("keyup", int_inpt_only, false);

Demo

Fabrício Matté
  • 65,581
  • 23
  • 120
  • 159
  • Hmm you suggest `.call` and cory suggests `.apply` is there any differences ? – Sir Jul 09 '13 at 22:17
  • Not many. They have the same effect, just that `apply`'s 2nd parameter takes an array of arguments while `.call()` uses passes the 2nd to nth parameters as arguments. – Fabrício Matté Jul 09 '13 at 22:18
  • Is there a way to stop it displaying the letter in the input box before removing it again ? – Sir Jul 09 '13 at 22:22
  • In modern browsers you can use `"input"` instead of `"keyup"`. That should solve the delay I believe. `=]` – Fabrício Matté Jul 09 '13 at 22:23
1

Try assigning the event handler like this:

inpt.addEventListener("keyup", 
    function(e, max) { int_inpt_only.apply(this, [e, max]); } , false);
Cᴏʀʏ
  • 97,417
  • 19
  • 158
  • 183
  • Hmm you suggest `.apply` and Frabricio suggests `.call` is there any differences ? – Sir Jul 09 '13 at 22:17
  • Some slight differences in syntax but basically the same functionality: http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply – Cᴏʀʏ Jul 09 '13 at 22:19
  • 1
    `apply` tends to be slower than `call`, so use `call` if possible (which is in this case) – Koen. Jul 09 '13 at 22:49
  • @Koen: You are very correct. I didn't know this, but the difference is rather suprising (at least in Chrome): http://jsperf.com/function-versus-function-call-versus-function-apply – Cᴏʀʏ Jul 10 '13 at 13:46