Reputation: 16002
I'm trying to write a method on vue, why the 'clickA' can not work, but 'clickB' workable?
Note: The solution should let the throttle function work like the 'clickB'.
new Vue({
el: '#app',
methods: {
clickA: function() {
_.throttle(function() {
var date = new Date();
var time = date.toLocaleTimeString();
console.log('A clicked', time)
}, 1000)
},
clickB: _.throttle(function() {
var date = new Date();
var time = date.toLocaleTimeString();
console.log('B clicked', time)
}, 1000)
}
});
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/[email protected]/lodash.min.js"></script>
<div id="app">
<button type="button" @click="clickA">A</button>
<button type="button" @click="clickB">B</button>
</div>
Upvotes: 1
Views: 65
Reputation: 61
_.throttle
returns a throttled function.
So you can define a new function:
var slowThing = _.throttle(fastThing)
Or you can define a function as a property:
object: {
slowThing: _.throttle(fastThing)
}
But in clickA
above, the throttled function is isn't assigned:
slowThing: function() {
// this creates a new function but doesn't execute it
_.throttle(fastThing)
}
Upvotes: 0
Reputation: 6791
_.throttle
returns a new function. Think about this, it may be a little hard to wrap your head around, but it makes sense!
clickB
is bound to that function which _.throttle
returns.
However, in clickA
, you're not binding the click action to that function which _.throttle
creates.
Upvotes: 1