Created
June 13, 2018 05:01
-
-
Save alexsasharegan/3adac3b79e441cb08e09b7dde235b9e0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { shallowCopy, deepCopy } from "@/core/object"; | |
import { ucFirst } from "@/core/string"; | |
/** | |
* Returns a dynamic mixin that will shallow clone the desired prop. | |
* Adds a mutable data attribute with the given alias (`${prop}Copy`), | |
* a reset method to reset value to the actual prop's value | |
* (`reset${prop}Copy` or `reset${customAlias}`), and handles watching | |
* the prop for updates. | |
*/ | |
export function shallowCloneMixin( | |
prop: string, | |
descriptor = { type: Object, required: true }, | |
alias = `${prop}Copy` | |
) { | |
return { | |
props: { | |
[prop]: descriptor, | |
}, | |
data() { | |
return { | |
[alias]: shallowCopy(this[prop]), | |
}; | |
}, | |
watch: { | |
// Watch prop value changes and recopy. | |
[prop](newData: any) { | |
shallowCopy(newData, this[alias]); | |
}, | |
}, | |
methods: { | |
// Reset re-copies from the untouched prop value. | |
[`reset${ucFirst(alias)}`]() { | |
this[alias] = shallowCopy(this[prop]); | |
}, | |
}, | |
}; | |
} | |
/** | |
* Returns a dynamic mixin that will deep clone the desired prop. | |
* This does not reconstruct any class types, and is thus discouraged. | |
* Deep copying is expensive and should be avoided whenever possible. | |
* Prefer to break nested data structures out into flatter copies, | |
* or make custom copies. | |
* | |
* Adds a mutable data attribute with the given alias (`${prop}Copy`), | |
* a reset method to reset value to the actual prop's value | |
* (`reset${prop}Copy` or `reset${customAlias}`), and handles watching | |
* the prop for updates. | |
*/ | |
export function deepCloneMixin( | |
prop: string, | |
descriptor = { type: Object, required: true }, | |
alias = `${prop}DeepCopy` | |
) { | |
return { | |
props: { | |
[prop]: descriptor, | |
}, | |
data() { | |
return { | |
[alias]: deepCopy(this[prop]), | |
}; | |
}, | |
watch: { | |
// Watch prop value changes and recopy. | |
[prop](new_data: any) { | |
this[alias] = deepCopy(new_data); | |
}, | |
}, | |
methods: { | |
// Reset re-copies from the untouched prop value. | |
[`reset${ucFirst(alias)}`]() { | |
this[alias] = deepCopy(this[prop]); | |
}, | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment