One can kick an observable calling its valueHasMutated
method to force a notification to the subscribers. What does valueWillMutate
do?
When subscribing to an observable, sometimes you want to know the previous value of the observable when it has changed. For example, when you have an observable selectedItem
(in a list of items), but each individual item also has a selected
property. When selectedItem
changes, you want to selected selected = false
on the previously selected item. You can do that like this:
selectedItem.subscribe(function (previous) {
previous.selected = false;
}, null, 'beforeChange');
valueWillMutate is used to trigger the beforeChange
event.
Edit: for even more utility, take a look at Knockout-2.2.0, subscribe get value before change AND new value. The highest-voted answer creates an extender that allows you to subscribe to an observable and use both the old and new value at the same time.
Edit 2: Just to clarify: you do not need to explicity call valueWillMutate
to get the beforeChange
event: Knockout does that for you when you operate on an observable. You only need to do it manually when you operate on the underlying value, or when you want to explicity trigger subscribers for some reason. My answer was written from the point of view of Knockout's internal implementation, which I didn't really make clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With