Steph8
Steph8

Reputation: 1583

Reset Knockout observable variables to its start value

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?

Upvotes: 3

Views: 798

Answers (1)

user3297291
user3297291

Reputation: 23372

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.

Upvotes: 3

Related Questions