0

I'm a little weak (or maybe a lot weak) with client side scripting. I am trying to implement a delayed call to do an ajax save based on waiting 500ms after the user stops typing.

I found this great solution here. But my resulting function needs the original element that triggered the save. How can I pass this value through?

Here is my calling code:

$('#OrderDetailsTabs').on('keyup', 'form[id^="frmWorkOrderHdr"] textarea', function (event) {
        var thisElement = this;
        delay(function (thisElement) {
            alert('Time elapsed!');
            saveWOHdr(thisElement);
            },
            1000);
    })

Here is the delay variable definition:

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();

saveWOHdr needs the originating element to be passed to it.

Community
  • 1
  • 1
crichavin
  • 4,672
  • 10
  • 50
  • 95
  • Simply remove the `thisElement` argument from the function you are passing to `delay()`. Everything else looks correct. – techfoobar Jul 16 '13 at 03:26

2 Answers2

1

This should work:

$('#OrderDetailsTabs').on('keyup', 'form[id^="frmWorkOrderHdr"] textarea', function (event) {
        delay(function () {
            alert('Time elapsed!');
            saveWOHdr(event.target);
            },
            1000);
    })

Because of closures in JavaScript, event is available to the anonymous function you pass into delay even after your event handler function exits. You can use event.target to figure out which element triggered the event.

go-oleg
  • 19,272
  • 3
  • 43
  • 44
0

It's just the result of setTimeout not giving any function arguments. The code you have should already work if you remove the argument from your function since it'll be undefined at the moment (as setTimeout isn't passing an argument).

$('#OrderDetailsTabs').on('keyup', 'form[id^="frmWorkOrderHdr"] textarea', function (event) {
    var thisElement = this;
    delay(function () {
        alert('Time elapsed!');
        saveWOHdr(thisElement);
        },
        1000);
})
blakeembrey
  • 424
  • 3
  • 8