Skip to content

Constructor not entirely suitable as created hook (has wrong this) #26

@nebaughman

Description

@nebaughman
"vue": "^2.6.11",
"vue-class-store": "^2.0.5",

Experimenting with vue-class-store as a replacement for Vuex and loving it so far. However...

The following example does not work as expected. Setting local properties in the constructor does work, but calling methods that reference this will have a bad reference.

@VueStore
class Store {
  counter = 0
  constructor() {
    this.counter = 256 // this works
    this.startCounting() // will not work (method will reference wrong `this`)
  }

  private startCounting() {
    setInterval(() => this.counter++, 1000) // does not work if called from constructor (wrong `this.counter`)
  }
}

Workaround (somewhat awkward):

@VueStore
class Store {

  counter = 0

  // fired immediately by Vue with correct `this`
  private "on:any_random_name" = {
    immediate: true,
    handler: this.startCounting
  }

  private startCounting() {
    setInterval(() => this.counter++, 1000)
  }
}

Decorator workaround (still awkward):

// decorator function
function Creatable(target: Function) {
  const uuid = createUUID() // for example
  target.prototype[`on:${uuid}`] = {
    immediate: true,
    handler: "created"
  }
}

@VueStore
@Creatable // must be AFTER @VueStore -- awkward!
class Store {
  counter = 0
  private created() { // pseudo-created hook
    setInterval(() => this.counter++, 1000) // has correct `this`
  }
}

Maybe this can be fixed in a more elegant way? Any advice is most welcome. Thanks for your work on this project!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions