melanke / Watch.JS

watch the changes of any object or attribute
Other
2.14k stars 219 forks source link

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

Open pegues opened 6 years ago

pegues commented 6 years ago

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 commented 6 years ago

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 commented 6 years ago

@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";