Skip to content
This repository has been archived by the owner on Jan 26, 2023. It is now read-only.

Commit

Permalink
feat: implement support for vue subclasses as models
Browse files Browse the repository at this point in the history
  • Loading branch information
JohannesLamberts committed Apr 20, 2019
1 parent f48c7e3 commit 392b57d
Showing 1 changed file with 32 additions and 11 deletions.
43 changes: 32 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,36 @@ const OPTIONS_DEFAULTS: ModelInstallOptions = {
globalModels: {},
}

function createModels(this: VueModelProvided, vue: VueConstructor, installOptions: ModelInstallOptions) {
function createModel(
this: Vue,
vue: VueConstructor,
key: string,
optionsOrClass: ComponentOptions<Vue> | VueConstructor,
installOptions: ModelInstallOptions,
) {
const isClass = typeof optionsOrClass === 'function'
// check for 'super' to enable later support for options like
// models: { Content: () => import('some-chunk') }
&& typeof (optionsOrClass as any).super === 'function'

const options = createModelOptions(
this,
key,
isClass ? {} : (optionsOrClass as ComponentOptions<Vue>),
installOptions.mixins,
)
const vm = new ((isClass ? optionsOrClass : vue) as VueConstructor)(options);

(this as any)[key] = this.$modelsProvided[key] = vm
this.$modelRegistry.register(vm)

this.$on('hook:beforeDestroy', () => {
this.$modelRegistry.unregister(vm)
vm.$destroy()
})
}

function createModels(this: Vue, vue: VueConstructor, installOptions: ModelInstallOptions) {
this.$modelsProvided = {}

if (!this.$options.models && this !== this.$root) {
Expand All @@ -83,16 +112,8 @@ function createModels(this: VueModelProvided, vue: VueConstructor, installOption

Object
.entries(models)
.map(([key, options]) => {
const vm = new vue(createModelOptions(this, key, options, installOptions.mixins));

(this as any)[key] = this.$modelsProvided[key] = vm
this.$modelRegistry.register(vm)

this.$on('hook:beforeDestroy', () => {
this.$modelRegistry.unregister(vm)
vm.$destroy()
})
.forEach(([key, options]) => {
createModel.call(this, vue, key, options, installOptions)
})
}

Expand Down

0 comments on commit 392b57d

Please sign in to comment.