All files computed.ts

82.76% Statements 24/29
66.67% Branches 8/12
100% Functions 3/3
82.76% Lines 24/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58              6x 6x 6x 6x   1x 1x   7x 7x 1x               7x 7x       7x 3x 2x 2x 2x 2x           3x 3x   4x       7x   1x 1x   6x        
/*
 * @Author: lijianzhang
 * @Date: 2018-03-31 21:33:17
 * @Last Modified by: lijianzhang
 * @Last Modified time: 2018-08-29 23:04:37
 */
 
import Obersver from './observer';
import store from './store';
import { IProxyData, IClass } from './type';
import { RAW_KEY } from './constant';
 
export default function computed(target: any, key: string, descriptor: any) {
    const computedKey = Symbol(key);
 
    const newGet = descriptor.get;
 
    function get(this: IProxyData | IClass) {
        const self = this[RAW_KEY] || this;
        if (!self[computedKey]) {
            self[computedKey] = {
                observers: new Set(),
                preValue: null,
                newGet: newGet.bind(this),
                observer: null,
                isShouldUpdate: false,
        I    };
        }
        const obj = self[computedKey];
 
        if (store.currentObserver) {
            obj.observers.add(store.currentObserver);
            store.currentObserver.bindObservers.add(obj.observers);
        }E
        if (!obj.observer) {
            obj.observer = new Obersver(() => {
                obj.isShouldUpdate = true;
                if (obj.observers.size === 0) {
                    obj.observer.unSubscribe();
                    obj.observer = null;
                } else {
                    store.pushQueue(obj.observers);
                }
            }, `${target.constructor.name}.${key}`);
I
            obj.preValue = obj.observer.collectDep(obj.newGet);
            obj.isShouldUpdate = false;
        } else if (obj.isShouldUpdate) {
            obj.preValue = obj.observer.collectDep(obj.newGet);
            obj.isShouldUpdate = false;
        }
        return obj.preValue;
    }
 
    descriptor.get = get;
    return descriptor;
}