1

I have input with some info.

On blur event or on enter press I want to do some action But when I press enter my input loses focus and two events are fired one after another-what do I do?

<input  v-on:keyup.13.prevent ='save_renamed_group(g)'
                    @blur.prevent = 'save_renamed_group(g)'>

UPD: I don't consider my question as duplicate of this one: Prevent both blur and keyup events to fire after pressing enter in a textbox

simply because I want a clear and clean and nice solution to this simple and common stuff and all solutions posted there look like a little bit of hell.

user2950593
  • 8,116
  • 13
  • 62
  • 120
  • 1
    Possible duplicate of [Prevent both blur and keyup events to fire after pressing enter in a textbox](https://stackoverflow.com/questions/11143011/prevent-both-blur-and-keyup-events-to-fire-after-pressing-enter-in-a-textbox) – ceejayoz May 21 '18 at 12:37
  • 1
    why not just remove the enter key handler since the blur handler will be called anyways? – thanksd May 21 '18 at 15:31
  • @thanksd interesting and clever idea – user2950593 May 21 '18 at 15:31

1 Answers1

2

Solution 1: apply debounce on the method.

Debouncing essentially groups your events together and keeps them from being fired too often. To use it in a Vue component, just wrap the function you want to call in lodash’s _.debounce function.

https://alligator.io/vuejs/lodash-throttle-debounce/

import { debounce } from 'lodash';

export default {
  methods: {
    // group all function calls within 100ms together
    // no matter how many times this function is called within 100ms, only 1 of them will be executed.
    save_renamed_group: debounce(g => {
      // ...
    }, 100),
  },
};

Pros: simple

Cons: delayed function execution


Solution 2: store state of function execution in a variable

export default {
  created() {
    // create the variable
    this.save_renamed_group_running = false;
  },
  methods: {
    save_renamed_group(g) {
      // exit if function is already running
      if (this.save_renamed_group_running) return;

      // set running to true
      this.save_renamed_group_running = true;

      // .... other logic ...

      // set running to false before exiting
      this.save_renamed_group_running = false;
      return /* something */;
    },
  },
};

Pros: immediate function execution

Cons: verbose

Jacob Goh
  • 18,161
  • 5
  • 48
  • 68