简体   繁体   中英

Click event fires multiple times with enter key being held

There is the knockout-3.3.0 & jquery-1.11.2 & bootstrap-3 application.

The template with click binding:

<div class="modal-footer">
    <button type="button" class="btn btn-primary" data-bind="click: $parent.Submit, text: 'Submit'"></button>
</div>

The viewmodel contains handler:

self.Submit = function (data, event) {
    console.log('fired');
    /* do some very important staff */
};

If I clicked on Submit button then the event fires once. But if I pressed and held Enter key and clicked on Submit button helding the Enter key being pressed then the event fires from 10 to 20 times.

There is an option to modify the handler like this:

self.isSubmitting = ko.observable(false);
self.Submit = function (data, event) {
    if (self.isSubmitting()) {
        return;
    }

    console.log('fired');
    self.isSubmitting(true);

    /* do some very important staff */

    self.isSubmitting(false);
};

But I'd prefer some more general solution instead of modifying each click handler in the application.

So, what do you think? Thank you in advance!

Edit : The problem is fosus on the button after it was clicked. Modifying the event binding is not the option because this behaviour is correct. That's why the solution is to modify the handler to avoid unwanted execusion using isSubmitting boolean variable.

Unsure if this will work with your UX design, but I assume you could use the mouseup event to get around this?

Edit You will want to do this for touch devices as well, so you'll want to bind to 2 events 'mouseup' and 'touchend', unsure of the syntax in knockout to so this, so I have done what I assume to be correct below, might be a knockout error there though.

<div class="modal-footer">
    <button type="button" class="btn btn-primary" data-bind="mouseup: $parent.Submit, text: 'Submit', touchend: $parent.Submit"></button>
</div>

Otherwise you could apply a throttle / debounce. For ease of reference, check out lodash documentation on the usage of throttle:

https://lodash.com/docs/4.17.10#throttle

I'm not saying to import lodash purely for their throttle (it's like 70kb un gzipped), but that should give you the idea (the usage).

var waittime = 1000;
self.Submit = _.throttle(function (data, event) {
    console.log('fired');
    /* do some very important staff */
}, waittime);

I don't think that will help though, as it would still execute once the waittime had passed, assuming the user still had their finger/hand on the enter button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM