Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the `valueWillMutate` for in KnockoutJs?

Tags:

knockout.js

One can kick an observable calling its valueHasMutated method to force a notification to the subscribers. What does valueWillMutate do?

like image 604
Trident D'Gao Avatar asked Jul 31 '14 14:07

Trident D'Gao


1 Answers

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.

like image 168
Hans Roerdinkholder Avatar answered Sep 22 '22 02:09

Hans Roerdinkholder