GianlucaGuarini / icaro

Smart and efficient javascript object observer, ideal for batching DOM updates (~1kb)
MIT License
573 stars 29 forks source link

Listening to child listener #3

Closed mokkabonna closed 7 years ago

mokkabonna commented 7 years ago

EDIT: I saw this now: "// listen only the changes happening on the root object"

Would it be possible though to add a listen to all function?

Old post:


From the docs I expected the following code to trigger 2 listen callbacks:

const obj = icaro({})

obj.listen(function(changes) {
  console.log(obj.toJSON());
})

obj.nested = {}

setTimeout(function() {
  obj.nested.someVal = 'hello'
}, 100)

But all I get is

{ nested: {} }

Am I understanding it wrong? Listening to obj.nested does trigger a change, but I expected it to also trigger a parent listen.

mokkabonna commented 7 years ago

I did manage to the the desired behaviour with the following code.

var state = icaro({});

state.listen(function listener(changes) {
    changes.forEach(function(val) {
        if (val && val.listen) {
            val.listen(listener);
        }
    });

    console.log(state.toJSON());
});

state.nested = {};

setTimeout(function() {
  state.nested.test = 5;
}, 100);

A listenAll function would still be welcome though. Closing.