Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS this in lodash throttled method

Tags:

lodash

vue.js

I am trying to throttle a method in my VueJS application. I tried the following at first:

export default {
    data () {
        return {
            foo: 'bar'
        }
    },
    methods: {
        doSomething () {
            console.log('olas')
        }
    },
    created () {
        _.throttle(this.doSomething,200)
    }
}

But the doSomething method was just not fired: https://jsfiddle.net/z4peade0/

Then, I tried this:

export default {
    data () {
        return {
            foo: 'bar'
        }
    },
    methods: {
        doSomething: _.throttle( () => {
            console.log('olas')
        },200)
    },
    created () {
        this.doSomething()
    }
}

And the functiong gets triggered: https://jsfiddle.net/z4peade0/1/

Problem is, I can't access the foo property inside the throttled method:

export default {
    data () {
        return {
            foo: 'bar'
        }
    },
    methods: {
        doSomething: _.throttle( () => {
            console.log(this.foo) // undefined
        },200)
    },
    created () {
        this.doSomething()
    }
}

I tried to do something like:

const self = {
    ...
    methods: {
        doSomething: _.throttle( () => {
            console.log(self.foo) 
        },200)
    },
    ...
}

export default self

without success

How could I use lodash throttled method on a VueJS method, and using this context?

like image 225
Hammerbot Avatar asked Mar 21 '17 12:03

Hammerbot


People also ask

What is throttle in Lodash?

throttle() method in lodash is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds.

Can I use Vue and jQuery together?

Yes you can inject some Vue into a project built with regular JavaScript or jQuery. It's not all or nothing. You can pass data between JavaScript and Vue because it you're dealing with JavaScript objects.

What is Lodash in Vuejs?

Lodash is a JavaScript library that is packed with a bunch of goodies 🍬. Unlike Halloween goodies that means you have to do laps around your neighborhood to burn those extra calories.


1 Answers

You're using an arrow function, which binds the wrong context (this). You should use a plain function:

    doSomething: _.throttle( function () {
        console.log('olas', this.foo);
    },200)
like image 123
Roy J Avatar answered Oct 13 '22 01:10

Roy J