[Reactive] Run functions when data changes

Zhentiw發表於2024-09-24
function observe(obj) {
    for (const key in obj) {
        let internalValue = obj[key];
        const funs = new Set()
        Object.defineProperty(obj, key, {
            configurable: false,
            get: function () {
                if (window.__func) {
                    funs.add(window.__func)
                }
                return internalValue;
            },
            set: function (val) {
                internalValue = val;
                for (let i = 0; i < funs.size; i++) {
                    funs[i]()
                }
            },
        });
    }
}

function autorun(func) {
    window.__func = func
    func()
    window.__func = null
}

const user = {
    firstName: 'John',
    lastName: 'Doe',
    age: 20
}

observe(user)

function showFirstName() {
    console.log(user.firstName)
}

function showLastName() {
    console.log(user.lastName)
}

function showAge() {
    console.log(user.age)
}

autorun(showFirstName)
autorun(showLastName)
autorun(showAge)

相關文章