How to Activate a Function When Some Variable Changes

How to run a function in JavaScript every time a variable changes?

Use object.watchdocs and if it is not supported natively look at this implementation: Object.watch() for all browsers?

Run Function on Variable Change

You set value to property of an object, use set, get.

const x = {};
let value = 0;
function fn(oldValue, newValue) { console.log(`${oldValue} has been changed to ${newValue}`);}
Object.defineProperty(x, "prop", { get() { return value }, set(val) { fn(value, val); value = val; }});
x.prop = 1;
x.prop = 10;

how to activate a function when some variable changes?

Unfortunately, there is no direct way to do this. But an acceptable solution would be to use a setter:

private int a = 1;

public void setA(int a) {
this.a = a;
update();
}

public static void main(String[] args) {
Main m = new Main();
m.setA(2);
}

Execute Function when a State Variable Changes inside of a useEffect() Hook

Store graph in a React ref so it persists through rerenders. In hideN use an Optional Chaining operator on graphRef.current to call the findById function.

Add hideNode state as a dependency to the useEffect hook and move the hideN call out of the conditional block that is only instantiating a graph value to store in the ref.

const graphRef = useRef(null);
const ref = useRef(null);

//Hide Node State
const [hideNode, sethideNode] = useState("");

const hideN = () => {
const node = graphRef.current?.findById(hideNode);
node.hide();
};

useEffect(() => {
if (!graphRef.current) {
graphRef.current = new G6.Graph(cfg);
graphRef.current.data(data);
graphRef.current.render();
}
hideN();
}, [hideNode]);

How can i call JUST ONCE a function when a variable changes its value? c#

One thing you can do is use a public property for accessing the Count, and store the value of the property in a private backing field. This way you can compare the incoming value in the setter (which is called when someone is setting the Count property) to the current count. If it's different, then call DoSomething (and update your backing field):

Property with backing field and custom setter

private int count = 0;

public int Count
{
get
{
return count;
}
set
{
// Only do something if the value is changing
if (value != count)
{
DoSomething();
count = value;
}
}
}

Example Usage

static class Program
{
private static int count = 0;

public static int Count
{
get
{
return count;
}
set
{
// Only do something if the value is changing
if (value != count)
{
DoSomething();
count = value;
}
}
}

private static void DoSomething()
{
Console.WriteLine("Doing something!");
}

private static void Main()
{
Count = 1; // Will 'DoSomething'
Count = 1; // Will NOT DoSomething since we're not changing the value
Count = 3; // Will DoSomething

Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();
}
}

Output

enter image description here

how to trigger function in another object when variable changed. Python

Whenever a property of class is changed, setattr() function is called. You can override this by defining __setattr__(self, property, value) function in your class.

You need to make your required function call within this __ setattr__(). Below is the sample example based on your requirement:

class Centre(object):
def __init__(self):
self.queue = None
self.va = 0

def whenChanged(self):
next = self.queue.dequeue()
next.function()

def __setattr__(self, key, value):
self.key = value
self.whenChanged() # <-- Your function

Whenever you will attempt to change the value of any of class's property, this __settattr__ function will be called.

Angular 9 call a function when a variable changes value

Finally spent the day researching this. You want to use multicast observables from RxJS. It's very efficient code and should be native to your Angular app.

For the above example, in the globals.ts file, add...

import { Observable, Subject } from 'rxjs';

public interestingString:string = 'blah';

public updateString$ = Observable.create((observer) => {
observer.next(this.interestingString);
});

public interestingString$ = new Subject();

Now, in as many component .ts files as you like, add this...

ngOnInit(): void {

this.globals.interestingString$.subscribe((data) => {
console.log('interestingString$: ' + data);
//do whatever else you want to do when the interestingString changes
});
//...all your other code
}

This next step can be in any other module or this one... like maybe later as a click event on a button; when you want to change the value so that all the subscribers update at once...

this.globals.interestingString = "I saw Cher in real life today! Man, did she dish on Greg Allman!";
//updateProfile will automatically .next the current profile
// ...and then will push to all subscribers of profile$
this.globals.updateString$.subscribe(this.globals.interestingString$);


Related Topics



Leave a reply



Submit