Skip to content

Commit

Permalink
feat: model $setAttr
Browse files Browse the repository at this point in the history
  • Loading branch information
khczhihao authored and khczhihao committed Dec 3, 2022
1 parent b184264 commit 57e77a6
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
17 changes: 17 additions & 0 deletions core/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ import Container from './container'
import ModelUnit from './model-unit'
import { EventCallback, MakeModelOptions } from './types'

type KeysOfTypeStrict<T, U> = {
[P in keyof T]: T[P] extends U ? (U extends T[P] ? P : never) : never
}[keyof T]

type PickByTypeStrict<U, T> = Pick<T, KeysOfTypeStrict<T, U>>

class Model {
_model: ModelUnit
_container!: Container
Expand Down Expand Up @@ -85,6 +91,17 @@ class Model {
return this._model.getBody()
}

$setAttr(data: Partial<Omit<PickByTypeStrict<number | boolean | string, this>, keyof Model>>) {
for (let key in data) {
if (key in this._model.body) {
let type = Utils.getType(this._model.body[key])
if (['string', 'number', 'boolean', 'empty'].includes(type)) {
this._model.body[key] = (data as any)[key]
}
}
}
}

$keys() {
return this._model.getKeys()
}
Expand Down
2 changes: 1 addition & 1 deletion dist/index.js

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions dist/model.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import Utils from './utils';
import Container from './container';
import ModelUnit from './model-unit';
import { EventCallback, MakeModelOptions } from './types';
type KeysOfTypeStrict<T, U> = {
[P in keyof T]: T[P] extends U ? (U extends T[P] ? P : never) : never;
}[keyof T];
type PickByTypeStrict<U, T> = Pick<T, KeysOfTypeStrict<T, U>>;
declare class Model {
_model: ModelUnit;
_container: Container;
Expand Down Expand Up @@ -29,6 +33,7 @@ declare class Model {
$init(data?: any): this;
$copy(options?: MakeModelOptions): this;
$body(): any;
$setAttr(data: Partial<Omit<PickByTypeStrict<number | boolean | string, this>, keyof Model>>): void;
$keys(): string[];
$reset(key?: keyof Omit<this, keyof Model>): void;
$rules(name: keyof Omit<this, keyof Model>): import("./types").RuleCallback[];
Expand Down
8 changes: 8 additions & 0 deletions docs-code/structure/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,14 @@ model.$copy = function(options?: { save?: boolean }) => Model
model.$body = function() => { [key: string]: any }
```
### $setAttr
批次更新常數屬性,意指更新屬性為 `number` | `string` | `boolean` | `null` | `undefined` 的值。
```ts
model.$setAttr = function(data: { [key: string]: any }) => void
```

### $keys

回傳 [body](#body) 與 [refs](#refs) 的 key 值。
Expand Down

0 comments on commit 57e77a6

Please sign in to comment.