Skip to content
This repository has been archived by the owner on Mar 22, 2022. It is now read-only.

How to Check if Value Has Changed if Same Value Applied? #121

Open
pegues opened this issue Jan 23, 2018 · 2 comments
Open

How to Check if Value Has Changed if Same Value Applied? #121

pegues opened this issue Jan 23, 2018 · 2 comments
Labels

Comments

@pegues
Copy link

pegues commented Jan 23, 2018

I'm doing the following to check for changes to app.viewerData.state:

`

WatchJS.watch(app.viewerData, ['state'], function(){
	// Viewer Visibility
	if(app.viewerData.state == 1){
		// Create New Viewer
		console.log('Viewer State Set to: ' + app.viewerData.state);
	} else {
		// Close Viewer and Reset All Viewer Features
		console.log('Viewer State Set to: ' + app.viewerData.state);
	}
});

`

The issue I'm experiencing is getting a watch response even if the value changes from 1 to 1. I'd only want a response if the value changes from a previously different value, such as from 0 to 1, or 1 to 0. If the value changes from 1 to 1, or 0 to 0, I'd like there to be no change. How can I watch for this without using server-side code and not having to store previous values in an array? Is this ability already built into Watch.JS?

@pegues
Copy link
Author

pegues commented Jan 23, 2018

It looks like an array needs to be created to store the current values. Then do conditions to compare against what is stored in the array.

If an easier and cleaner way is available in Watch.JS, please let me know. It would be nice to not have to manage multiple conditions along with swapping array node values.

@melanke
Copy link
Owner

melanke commented Mar 15, 2018

@pegues maybe this is what you want:
http://jsfiddle.net/XnbXS/21/

//defining our object no matter which way we want
var ex1 = {
    attr1: "initial value of attr1",
    attr2: "initial value of attr2"
};

//defining a 'watcher' for an attribute
watch(ex1, "attr1", function(prop, action, newvalue, oldvalue){
    alert(prop+" - action: "+action+" - new: "+newvalue+", old: "+oldvalue+"... and the context: "+JSON.stringify(this));
});

//when changing the attribute its watcher will be invoked
ex1.attr1 = "other value";

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants