I'd like to be able to throttle a method in a component and be able to call its cancel() method but can not do so.
https://jsfiddle.net/roblav96/zbb8keps/
https://lodash.com/docs#throttle
Is there any way we can make this work?
Make the function in methods
the bare, un-throttled function. And then make a computed property which returns a wrapped version.
var $vm = new Vue({
methods: {
socket: function() {
console.log("this.socket()")
}
},
computed: {
throttledSocket: function() {
return _.throttle(this.socket, 1000)
}
}
})
$vm.throttledSocket()
$vm.throttledSocket()
$vm.throttledSocket()
$vm.throttledSocket.cancel()
@sirlancelot Thank you very much sir!!! :D
Any examples of using this in combination with a watcher? I was hoping something like the following would work.. The method fires, but it's throttled.
computed: {
throttleUpdates() {
return _.throttle(this.updateFilters, this.throttle);
}
},
methods: {
updateFilters() {
this.$events.fire(this.event, this.filters);
}
},
watch: {
filters: {
deep: true,
handler() {
this.throttleUpdates()
}
}
}
Why do you need the computed method? I seems to work the way OP posted, except that the debounced method lacks cancel method.
Im not sure if I figured it out or just moved on, but I know it's no longer an issue.
Oh, I wasn't actually talking about your problem. I just spent almost 2 hours figuring out why my debounced function lacks the cancel method. The debounce works otherwise just fine, but I need to use the computed trick if I want to use the cancel method of the debounced function.
So now I know how to fix it, but I still have no idea why it needs to be done that way. Here's a bit more obvious (imo) example: CodePen
Vue wraps all functions under methods
in a bound function so that this
is defined properly. The wrapped function doesn't contain the cancel
method and even if it did, it's likely not going to work properly if the component is used multiple times on the page.
Using a computed property ensures that a debounced method is created for each component instance.
Makes sense, thanks!
Most helpful comment
Make the function in
methods
the bare, un-throttled function. And then make a computed property which returns a wrapped version.