Skip to content

Instantly share code, notes, and snippets.

@nomyfan
Last active February 8, 2021 09:22
Show Gist options
  • Save nomyfan/d0d06799a9d48c65999319ef897e2441 to your computer and use it in GitHub Desktop.
Save nomyfan/d0d06799a9d48c65999319ef897e2441 to your computer and use it in GitHub Desktop.
Multi-binding props and data shortcuts
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