Search code examples
javascriptvuejs3pinia

Pinia access function inside click function using this


I have a pinia store that runs some D3.js functions. Within a .on() function, I am trying to access this.piniaAction, not the this that is a SVG path.

For example:

export const useStore= defineStore('myStore', {
    actions: {
        piniaAction() {
            //Some stuff is done here
        },
        d3Action() {
            const svg = d3.select("#id")
            const group = svg.append("g")
            group.append("rect")
               .on("click", function(){
                   let myRect = d3.select(this) // This correctly gets the scoped svg element
                   this.piniaAction() //I want this to access the pinia action, not svg element
                }   
         }
     }
}

I can't find anything that helps me access the pinia action within the .on() function scope.


Solution

  • learn about this in javascript it's a complicated concept

    you can solve the problem using arrow function or set temp variable:

    arrow function

    export const useStore= defineStore('myStore', {
        actions: {
            piniaAction() {
                //Some stuff is done here
            },
            d3Action() {
                const svg = d3.select("#id")
                const group = svg.append("g")
                group.append("rect")
                   .on("click", () => {
                       let myRect = d3.select(this) // This correctly gets the scoped svg element
                       this.piniaAction() //I want this to access the pinia action, not svg element
                    }   
             }
         }
    }
    

    temp var

    export const useStore= defineStore('myStore', {
        actions: {
            piniaAction() {
                //Some stuff is done here
            },
            d3Action() {
                const $this = this
    
                const svg = d3.select("#id")
                const group = svg.append("g")
                group.append("rect")
                   .on("click", function(){
                       let myRect = d3.select(this) // This correctly gets the scoped svg element
                       $this.piniaAction() //I want this to access the pinia action, not svg element
                    }   
             }
         }
    }