sp9
sp9

Reputation: 755

Best way of cloning/copying a observable in Knockout

I have a knockout Model

  self.newItem = ko.observable({
        manufacturer: ko.observable(),
        itemnumber: ko.observable(),
        itemDescription: ko.observable(),
        priceclass: ko.observable()     

    });

and I have another one which has the same properties but only the itemnumber is observable.

 self.newItemToInsert = ko.observable({
        manufacturer: "",
        itemnumber: ko.observable(),
        itemDescription: "",
        priceclass: ""  

    });

I have another observable array to store the items

self.AllItems = ko.observableArray();

Now my question is how can I copy the newitem to newItemToInsert observable so I can save it to AllItems array and have the itemnumber be observable for different rows in the array. So if I add 10 items I want to be able to track the data changes in each of the 10 itemnumber properties.

Thanks

Upvotes: 0

Views: 300

Answers (1)

Mateen Kajabadi
Mateen Kajabadi

Reputation: 3634

If I got your question correctly ,you can have a separate view model for your items and for each items you create a new instance of that model. Then inside your Item View Model you define observable for any variables that you want.

Example :https://jsfiddle.net/9aLvd3uw/222/

VM:

var MainViewModel = function () {
   var _self = this;
   var i = 1;
   _self.Items = ko.observableArray([]);
   //Fake Data
   _self.Items.push(new ItemViewModel({ "manufacturer": "Co.0", "itemnumber": 123 ,"itemDescription": "Desc 0" , "priceclass" : "Class 0"}));
   //Add a new item with fake data
   self.ClickMe = function (){
     _self.Items.push(new ItemViewModel({ "manufacturer": "Co."+i, "itemnumber": 123 + i ,"itemDescription": "Desc" +i , "priceclass" : "Class "+i}));
     i++;
   }
}

var ItemViewModel = function (data) {
  var _self = this;
  _self.manufacturer = data.manufacturer;
  _self.itemnumber = ko.observable(data.itemnumber);
  _self.itemDescription = data.itemDescription;
  _self.priceclass = data.priceclass;
}
 ko.applyBindings(MainViewModel);

Upvotes: 1

Related Questions