What is `valueWillMutate` for KnockoutJs?

You can call an observable call to its valueHasMutated method to force notification of subscribers. What does valueWillMutate do?

+6
source share
1 answer

When subscribing to an observable, sometimes you want to know the previous value of the observable when it changed. For example, when you have an observable selectedItem (in the list of elements), but each individual element also has a selected property. When selectedItem changes, you want to select selected = false for the previously selected item. You can do it like this:

 selectedItem.subscribe(function (previous) { previous.selected = false; }, null, 'beforeChange'); 

valueWillMutate is used to fire the beforeChange event.

Edit: for even more utility, see Knockout-2.2.0, sign the get value before the change, and the new value . The above answer creates an expander that allows you to subscribe to the observable and at the same time use both the old and the new value.

Edit 2: just make it clear: you don't need to call the valueWillMutate expression to get the beforeChange event: the knockout does this for you when you work with the observable. You only need to do this manually when you are working with a base value, or when you want triggers to trigger for some reason. My answer was written in terms of an internal Knockout implementation, which I really haven’t clarified.

+7
source

Source: https://habr.com/ru/post/973170/


All Articles