melanke / Watch.JS

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

Bug when watching new properties #108

Open bloodcarter opened 7 years ago

bloodcarter commented 7 years ago

I tried your example from official docs, but it doesn't catch any changes. Here the full code:

'use strict';

var WatchJS = require("watchjs")
var watch = WatchJS.watch;
var unwatch = WatchJS.unwatch;
var callWatchers = WatchJS.callWatchers;

var ex = {
    l1a: "bla bla",
    l1b: {
        l2a: "lo lo",
        l2b: "hey hey"        
    }
};

watch(ex, function (prop, action, difference, oldvalue){

    console.log("prop: "+prop+"\n action: "+action+"\n difference: "+JSON.stringify(difference)+"\n old: "+JSON.stringify(oldvalue)+"\n ... and the context: "+JSON.stringify(this));    

}, 0, true);

ex.l1b.l2c = "new attr"; //it is not instantaneous, you may wait 50 miliseconds

setTimeout(function(){
    ex.l1b.l2c = "other value";
}, 100);
melanke commented 6 years ago

This implementation of watching new values isn't recommended, and I just realised it has a bug, probably will be remade in the next version.

You should use like this: http://jsfiddle.net/1jwntatp/

//defining our object no matter which way we want
var ex = {
    l1a: "bla bla",
    l1b: {
        l2a: "lo lo",
        l2b: "hey hey",
        l2c: null
    }
};

watch(ex, function (prop, action, difference, oldvalue){

    alert("prop: "+prop+"\n action: "+action+"\n difference: "+JSON.stringify(difference)+"\n old: "+JSON.stringify(oldvalue)+"\n ... and the context: "+JSON.stringify(this));    

});

ex.l1b.l2c = "new attr";
kolorafa commented 5 years ago

The example: "Do you want to know when new attributes change too?" works but somehow not if you have level set o 0, if you set it to eg. 10 it works. (At least in browser)