Reputation: 27
I'm currently in the process of converting our Backbone application to ES6 syntax like e.g. this:
action: function(e){},
Becomes
action(e) {}
However, now I'm having this code:
throttleEvent: _.throttle(function(e) {
//do stuff
}, 500);
}
And I can't seem to find how to convert this to valid syntax. I tried
throttleEvent _.throttle((e) => {
//do stuff
}, 500);
}
And
throttleEvent() {
return _.throttle((e) => {
//do stuff
}, 500);
}
But these all failed to work.
Help converting this to the valid syntax would be appreciated.
Upvotes: 1
Views: 79
Reputation: 3253
Well I'm not quite sure if the short syntax is applicable for your example.
Lets have a look at your start
action: function(e){},
you have an object, that object has a property called "action" and that property holds a function that later then can be called by obj.action().
Now to your example
throttleEvent: _.throttle(function(e) {}
Again you have an object, that has a property called throttleEvent. But the main difference is the value. The value is the return Value of the function _.throttle().
Taking from the documentation (https://lodash.com/docs/4.17.4#throttle)
Creates a throttled function that only invokes func at most once per every wait milliseconds
So your property actually holds the function that you got returned from the library. That explains why your second approach does not work. Because in this version every time you call the object property, you create a new throttle function. (And to your first solution I think this is invalid syntax)
I think the best approach if you really want to use the short syntax is, assigning the throttle function to a variable before and then use it
For example something like this
const throttleFunction = _.throttle((event) => {
//do stuff
}, 500);
const obj = {
throttleEvent(event): any {
return throttleFunction(event);
},
};
But then it is to decide whether the ES6 syntax makes sense in this case or if you just stick with your original version
throttleEvent: _.throttle(function(e) {
//do stuff
}, 500)
Just because there is a different syntax available, does not mean you always have to use the new one. In some cases the "old one" makes actually more sense
Upvotes: 3