Can a field initialized to an observable object become an array in knockout.js? -


i reading existing code. initially, code initializes property 'data':

self.data = ko.observable({}); 

but afterwards, in function code assigns 'data' below. self.data not set observablearray below, used though array. no other code touches self.data before line when hits line before assignment, still ko.observable({}).

self.data()[0] = ko.observable(""); 

i thinking legal syntax converting observable object array in knockout.js, if try put alert length alert(self.data().length), undefined.

my question code do?

it isn't observable array. it's object. javascipt object can access it's properties dot notation or index notation. link

since javascript dynamically typed can add new properties existing objects.

the following code adding new observable property existing object instance.

self.data()[0] = ko.observable(""); 

here example visualize what's going on.

var vm = function(){    var self = this;    self.data = ko.observable({});    self.datastring = ko.computed(function(){return json.stringify(self.data(), null, 2);});      self.propertyname = ko.observable(0);    self.propertyvalue = ko.observable('somevalue');      self.update = function(){      //this adds new property or updates existing property of object self.data observable references.      //the name of property value of self.propertyname observable value typed first textbox in ui.      //the value of property value of self.propertyvalue observable bhe value typed second textbox in ui.      self.data()[self.propertyname()] = self.propertyvalue();      //need force update since data observable wasn't directly modified      self.data.valuehasmutated();     };        self.replace = function(){      //replace existing value new object      var data = {};      data[self.propertyname()] = self.propertyvalue();      self.data(data);    };  }    $().ready( function(){    ko.applybindings(new vm());  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>    property name <input data-bind="textinput:propertyname" /> <br />  property value <input data-bind="textinput:propertyvalue" /> <br />    <button data-bind="click:update">update</button>  <button data-bind="click:replace">replace</button><br />  self.data observable represented json string:  <pre data-bind="text:datastring"></pre>


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -