3

I'm curious to know if Knockout implement a method to reset a observable variable to its start value. For example:

var test = ko.observable("test");

test("ciao");
test.reset();

value come back to "test". Exist something like this or a field that save the start value?

Steph8
  • 1,483
  • 2
  • 16
  • 32
  • Include it in a viewmodel and just create a new instance persay to initialize the values – Nkosi Jan 17 '17 at 15:39

1 Answers1

3

I'm not sure if adding functions to an observable via an extender is good practice, but you could add this functionality like so:

ko.extenders.canReset = function(target, enabled) {
  // If enabled, we assign a reset method bound to target's current value:
  return enabled
    ? Object.assign(target, { reset: target.bind(null, target()) })
    : target;
};

var myObs = ko.observable(10).extend({ canReset: true });
myObs.subscribe(console.log.bind(console, "new value:"));

myObs(20);
myObs(30);

// Reset
myObs.reset();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

If it feels wrong to "randomly" add a method to the observable, you could also look in to the fn-way of adding functionality.

user3297291
  • 22,592
  • 4
  • 29
  • 45