【问题标题】:ES6 Proxy: set property trap with debounce, is it possible to avoid dictionary of callbacks?ES6 Proxy:使用去抖动设置属性陷阱,是否可以避免回调字典?
【发布时间】:2021-03-04 22:35:11
【问题描述】:

目标:在用户输入时将任何更改的表单字段作为“名称-值”对,并在键入时进行去抖动。 示例模板(person 是双向绑定模型)。

<form>
  <q-input v-model="person.familyName" />
  <q-input v-model="person.givenName" />
  ...
</form>

我让它与 ES6 代理一起工作,但似乎有代码异味与去抖动回调字典: 每个属性都将自己的回调放到字典中,以免干扰其他字段。

// callback per 'field name' to prevent from skipping changes
// while fast typing with Tab button to switch between fields.
const debounces: { [key: string]: (...args: any[]) => any } = {};

const person = new Proxy(someSourceModel, {
    set: (target, key: string, value, receiver) => {
        Reflect.set(target, key, value, receiver);

        if (!debounces[key])
            debounces[key] = debounce(300, (key, value) => // throttle-debounce lib
            {
                // Do anything with changed key-value pair.
                // For example, send it with update to Dexie/PouchDB as
                // single field instead of whole object.
                console.log(`${String(key)}: ${String(value)}`);

                delete debounces[key]; // Cleanup when it fired.
            });

        debounces[key](key, value); // Fire it!
        return true;
    }
});

有什么方法可以避免回调字典?

Codesandbox 工作 example 包括在内。

【问题讨论】:

    标签: typescript quasar-framework es6-proxy


    【解决方案1】:

    lodash-es/debounce 的可能解决方案:当另一个属性发生变化时,立即调用 'flush' 挂起的去抖动。

    let lastProperty: string;
    
    const onChanged = debounce((key, value) => {
        // Do anything with changed key-value pair.
        // For example, send it with update to Dexie/PouchDB.
        console.log(`${String(key)}: ${String(value)}`);
    }, 300);
    
    const person = new Proxy(someSourceModel, {
        set: (target, key: string, value, receiver) => {
            Reflect.set(target, key, value, receiver);
    
            if (lastProperty != key) {
                lastProperty = key;
                onChanged.flush();
            }
    
            onChanged(key, value);
            return true;
        }
    });
    

    代码沙盒example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-02
      • 2018-03-10
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2013-04-22
      相关资源
      最近更新 更多