Last active
February 8, 2021 09:22
-
-
Save nomyfan/d0d06799a9d48c65999319ef897e2441 to your computer and use it in GitHub Desktop.
Multi-binding props and data shortcuts
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
type PropName = string; | |
type DateName = string; | |
export type PropDataNames = [PropName, DateName]; | |
export function syncState(...tuples: PropDataNames[]) { | |
const watcher = {} as { [index: string]: (v: any) => void }; | |
for (const tuple of tuples) { | |
const [propName, dataName] = tuple; | |
watcher[dataName] = function (v: any) { | |
const vm = this as any; | |
vm.$emit("update:" + propName, v); | |
}; | |
watcher[propName] = function (v: any) { | |
let accessor = this as any; | |
const nameChain = dataName.split("."); | |
for (let i = 0; i < nameChain.length - 1; i++) { | |
if (!accessor.hasOwnProperty(nameChain[i])) { | |
return; | |
} | |
accessor = accessor[nameChain[i]]; | |
} | |
if (accessor.hasOwnProperty(nameChain[nameChain.length - 1])) { | |
accessor[nameChain[nameChain.length - 1]] = v; | |
} | |
}; | |
} | |
return watcher; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment