MojoDK
MojoDK

Reputation: 4528

Save original values in Knockout

I read data into my viewmodel from JSON (from my server).

My user changes the viewmodel from some input fields, but I need to be able to undo it and bring back the original value from my original JSON.

Is it possible to store "attributes" on a viewmodel - an attribute like original value? So I can read it back?

Thanks

UPDATE...

Tried making a jsfiddle (which obviously doesn't work) to show what I would like to do:

var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
};

ViewModel.firstName.attribute("fieldtype", "string");
ViewModel.firstName.attribute("fieldlength", "30");
ViewModel.firstName.attribute("org-value", "Jane");

ko.applyBindings(new ViewModel("John", "Doe")); 

$("#cmd").clicked(function() {
    ViewModel.firstName(ViewModel.firstName.attribute("org-value"));
});

http://jsfiddle.net/MojoDK/kaymX/

Upvotes: 0

Views: 526

Answers (2)

Matt Burland
Matt Burland

Reputation: 45135

Adapting what you put in your fiddle, you could do something like this:

http://jsfiddle.net/kaymX/2/

var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
    this.firstName.attributes = {};
};

var myVM = new ViewModel("John", "Doe");

myVM.firstName.attributes["fieldtype"] = "string";
myVM.firstName.attributes["fieldlength"] = "30";
myVM.firstName.attributes["org-value"] = "Jane";

ko.applyBindings(myVM); 

$("#cmd").click(function() {
    myVM.firstName(myVM.firstName.attributes["org-value"]);
});

Although it might be easier to move setting of attributes inside the constructor for your view model. Also you could use the dot notation rather than the bracket notation, but I left it with accessing properties by strings since I assume you had a reason for having it that way in the first place.

Upvotes: 0

Anthony Chu
Anthony Chu

Reputation: 37520

I like to attach "attributes" to observables by adding properties to it (it's just a JavaScript function after all). Each property is attached to the observable it belongs to rather than stored in another structure elsewhere. Another benefit is that the properties on observables are also not serialized if you call ko.toJSON() on the view model.

function VM (value) {
  var self = this;

  self.foo = ko.observable(value);
  self.foo.original = value;

  self.revert = function () {
    self.foo(self.foo.original);
  };
}

JsBin: http://jsbin.com/biguvoqe/1/edit?html,js,output

Upvotes: 3

Related Questions