ZiadJ / knockoutjs-reactor

Recursively tracks changes within a view model no matter how deeply nested the observables are or whether they are nested within dynamically created array elements.
Other
74 stars 22 forks source link

How to "unwatch" / stop watching? #18

Closed bago closed 9 years ago

bago commented 9 years ago

Is there a way to stop watching a tree / unwatch the tree?

I see the code has "unwatch" / "dispose" methods but they seems "internal" and not public: am I missing anything?

ZiadJ commented 9 years ago

You can use .watch(false) to stop watching a particular property but it's not working down the tree yet. May be I should make it recursive by default. Also it does not destroy subscriptions, only puts them to sleep for performance reasons. Is there any reason you'd want to destroy them still?

bago commented 9 years ago

It's hard to explain my particular use-case: my application has logic based on the count of the subscribers to each subscribable and it uses (sometimes) instances of my undomanager to track changes in parts of the model. But, everyime I instantiate a new undomanager my subscriptions increase and are never decreased when I stop the undomanager.

What if I add this code at the end of ko.watch?

return {
  dispose: function() {
    watchChildren(target, null, [], true);
  }
}

so I can do something like:

var watch = ko.watch(....);
watch.dispose();

This doesn't sound a great solution, expecially because there are cases when you return a ko.computed as result of ko.watch: any better idea?

ZiadJ commented 9 years ago

I'm definitely with you when it comes to adding a dispose function. It's a great idea that's perfectly in line with the .computed and .subscribe use-case. However that might make the 'unwatch' function redundant but that's just me. So I'm holding on it for now. Can you check out my latest commit? I'd like to hear your say about it.

bago commented 9 years ago

I don't know what is better between the "return { dispose: }" and the ko['unwatch'] method. I'm currently using the first (the one you committed).