Reputation: 2301
I am trying to make a method which incorporates a debounce (using Lodash), which can have its wait parameter dynamically passed.
Here is sample code where I am trying to do this with an input field - it will log 'Hit' every time a user makes an input:
<template>
<div id="app">
<input @input='validateInput1(400)'>
</div>
</template>
<script>
import _ from 'lodash';
export default {
name: "App",
data() {
return {
};
},
methods: {
validateInput1: _.debounce(function() {
console.log('Hit 1!');
}, 400),
validateInput2(delay = 1000) {
function test() {
console.log('Hit 2!');
}
const doDebounce = _.debounce(test, delay);
doDebounce();
}
}
};
</script>
https://codesandbox.io/s/eloquent-wescoff-hs8wi?file=/src/App.vue
I am trying two different ways of achieving this. With validateInput1 method, I don't see how I can pass in the wait parameter.
With validateInput2 method, I can pass in the wait parameter, but the outer validateInput2 method runs immediately on input, when I need the entire method to run via wait. The validateInput1 method runs the entire method after a delay, but I can't pass in the wait parameter with validateInput1.
Upvotes: 1
Views: 582
Reputation: 1402
Though the code looks very ugly by itself, it just work.
<template>
<div id="app">
<input @input="validateInput2(10)" />
</div>
</template>
<script>
import _ from "lodash";
export default {
name: "App",
data() {
return {
debounce: null,
};
},
methods: {
validateInput2(delay = 1000) {
if (this.debounce) {
return this.debounce();
}
const deb = _.debounce(function test() {
console.log("Hit 2!");
}, delay); // I want to reuse it
this.debounce = deb;
return deb();
},
},
};
</script>
Though I do understand it looks much clearer to place the delay timeout in the template, instead of script, but definitely my answer seems worse than the validateInput1
solution you have had.
But anyway, if you can think of how to create a better and cleaner solution, feel free to share it with us.
Upvotes: 2
Reputation: 4464
One (quick) way achieving this is returning a function:
validateInput2(delay = 1000) {
function test() {
console.log('Hit 2!');
}
const doDebounce = _.debounce(test, delay);
return doDebounce;
}
And then in your template:
<input @input="validateInput2(400)()" />
What it does: First calling sends the delay. Second is calling composed function on @input
.
Upvotes: 0