Akryum / vue-supply

Create resources that can automatically be activated and deactivated when used (like subscriptions)
159 stars 16 forks source link

[feature request] `use` function for supplies #13

Open rossinek opened 6 years ago

rossinek commented 6 years ago

What problem does this feature solve?

Using use function to create mixin from supply definition is fine for components but it is not implemented to be used inside supplies. Sometimes there is a need for a resource that contains other resources. That's why I suggest adding the use method equivalent for in supply use.

Mixin created with use functions cause grasp call inside component's created hook, while inside supply the proper behaviour would be to call grasp on active state change (analogously for release).

What does the proposed API look like?

It could be a separate function or an additional flag for the use function.

Below I put an example helper that I created. Due to the fact that there is no access to registered supplies definitions and it is just simple proof-of-concept it accepts only supply definition as an argument. Another problem of this simple function is the lack of access to supplyCache (in my proof of concept it is imported).

import { supplyCache } from '@/supplies/cache'

export function include (supplyDef) {
  let name = ''
  const options = {
    created () {
      const resource = getResource(supplyDef, supplyCache)
      name = supplyDef.name

      if (!this.$supply) this.$supply = {}
      this.$supply[name] = resource
    },
    watch: {
      active (val, oldVal) {
        if (!this.$supply[name]) return
        if (val && !oldVal) {
          this.$supply[name].grasp()
        } else if (!val && oldVal) {
          this.$supply[name].release()
        }
      }
    }
  }
  return options
}

I am ready to prepare a better, more complete implementation. Cheers!