summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/vuex_shared/bindings.js
blob: 741690886b7063e061f96f1ab585eebfd61a3791 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * Returns computed properties two way bound to vuex
 *
 * @param {(string[]|Object[])} list - list of string matching state keys or list objects
 * @param {string} list[].key - the key matching the key present in the vuex state
 * @param {string} list[].getter - the name of the getter, leave it empty to not use a getter
 * @param {string} list[].updateFn - the name of the action, leave it empty to use the default action
 * @param {string} defaultUpdateFn - the default function to dispatch
 * @param {string} root - the key of the state where to search fo they keys described in list
 * @returns {Object} a dictionary with all the computed properties generated
 */
export const mapComputed = (list, defaultUpdateFn, root) => {
  const result = {};
  list.forEach((item) => {
    const [getter, key, updateFn] =
      typeof item === 'string'
        ? [false, item, defaultUpdateFn]
        : [item.getter, item.key, item.updateFn || defaultUpdateFn];
    result[key] = {
      get() {
        if (getter) {
          return this.$store.getters[getter];
        } else if (root) {
          return this.$store.state[root][key];
        }
        return this.$store.state[key];
      },
      set(value) {
        this.$store.dispatch(updateFn, { [key]: value });
      },
    };
  });
  return result;
};