Leonardo Wildt
Leonardo Wildt

Reputation: 2599

Knockout Observable Array Changes after push

I am pushing items into an observable array like so

var self = this;  
self.myArrayIwanttoAddTo = ko.observableArray([]);

self.myObjectIAmPushing = { 
 item1:ko.observable(),
 item2: ko.observable()
  }

  self.AddItemToUpdate = function (data) {
 self.myArrayIwanttoAddTo.push( new ko.observableArray([data]));
 }   

 self.AddMyData = function() {
  self.AddItemToUpdate(myObjectIAmPushing);
   self.myObjectIAmPushing.item1("");
   self.myObjectIAmPushing.item2("");
  }

I have also tried push(data)

I am able to add the first time but when i clear all the properties of my object and add it to the array i want to add to it changes the values to the values of the second push

so first push looks like this = {item1: 'A', item2: 'B'} when i clear all the properties and add again i get

{item1: 'C', item2:'D'},{item1: 'C', item2:'D'}

*Update thanks to the response from @Jason Spake

I got the following working like so

   self.AddItemToUpdate = function(data){
 function myObjecttoPush(item1,item2){
this.item1 = item1;
this.item2 = item2;
}
 var data2 = ko.toJS(data);
var items = new myObjecttoPush(data2.item1, data2.item2)
self.myArrayIwanttoAddTo.push(new myObjecttoPush(items.item1, items.item2));

I dont know that this is the correct way but it works?

I would still be interested in learning a better way.

Upvotes: 0

Views: 164

Answers (1)

Jason Spake
Jason Spake

Reputation: 4304

Without context I can't be sure which parts of your code are relevant so this might be an over simplified example. In javascript there are a few different ways you can create a new object. This example is using object initializers (the {...} syntax). See Working_with_Objects for more options.

function viewModel(){
  var self = this;  
  self.myArray = ko.observableArray([]);
  self.myArray.push({item1: "A", item2: "B"});

  self.AddMyData = function() {
    self.myArray.push({
      item1: ko.observable("C"),
      item2: ko.observable("D")
    });
  }
  
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<span data-bind="text: ko.toJSON(myArray)"></span>
<br/>
<input type="button" data-bind="click: AddMyData" value="Add C,D" />

Upvotes: 1

Related Questions