import { isArray, isUndefined } from 'underscore'; import { AddOptions, Collection } from '../common'; import ModuleModel from './ModuleModel'; type ModuleExt = TModel extends ModuleModel ? M : unknown; type ModelConstructor = { new (mod: ModuleExt, attr: any): TModel }; export default class ModuleCollection extends Collection { module!: ModuleExt; private newModel!: ModelConstructor; add(model: Array> | TModel, options?: AddOptions): TModel; add(models: Array> | TModel>, options?: AddOptions): TModel[]; add(model?: unknown, options?: AddOptions): any { //Note: the undefined case needed because backbonejs not handle the reset() correctly var models = isArray(model) ? model : !isUndefined(model) ? [model] : undefined; models = models?.map(m => (m instanceof this.newModel ? m : new this.newModel(this.module, m))) ?? [undefined]; return super.add(isArray(model) ? models : models[0], options); } constructor( module: ModuleExt, models: TModel[] | Array>, modelConstructor: ModelConstructor ) { super(models, { module, modelConstructor }); } preinitialize(models?: TModel[] | Array>, options?: any) { this.newModel = options.modelConstructor; this.module = options.module; } }