N
N
Nadim Zakirov2021-07-11 19:01:36
JavaScript
Nadim Zakirov, 2021-07-11 19:01:36

How to react to the fact of object change?

Now, as I do, I write a special editor function, through which I work everywhere with target objects. Roughly speaking, if I need to change something in an object, I don't do it directly, but call the editor function. However, I was thinking, maybe there are some other ways to react to a change in an object?

Ideally, I would like to stupidly hang up a certain handler and work with the object directly in the future.

PS I have a vague feeling that I have already asked this question, do not kick me hard if anything)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2021-07-11
@zkrvndm

You can use the reactivity system from the Vue framework. You don't need the whole framework. Just @vue/reactivity is enough (works on Proxy)
Example:

import { computed, effect, reactive } from "@vue/reactivity";

const obj = reactive({ foo: 1 }); // Реактивная переменная
const doubleFoo = computed(() => obj.foo * 2); // Вычисляемое свойство (Реактивная переменная которая автоматически пересчитывается когда изменяется какая-либо из использованных внутри реактивных переменных)
effect(() => console.log("doubleFoo value changed to:" + doubleFoo.value)); // Функция, запускается когда изменяется какая-либо из использованных внутри реактивных переменных)

// Каждую секунду изменяет значение obj.foo
// После чего автоматически пересчитывается значение doubleFoo 
// После изменения doubleFoo вызывается функция переданная в effect и выводится сообщение в лог
setInterval(() => obj.foo++, 1000)

https://codesandbox.io/embed/ecstatic-wind-68ez4?f...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question