user2380477
user2380477

Reputation:

How to add an object to an observableArray in knockout js?

I have the following javascript object which I use as an enum.

Object {Group1: 0, Group2: 1, Group3: 2, Group4: 3, Group5: 4}

Id like to be able to use it to create check boxes or drop downs using knockout templates basicly i need these values to be observable.

Ive tried adding the object to an observable array but it doesnt work. can any one help?

Upvotes: 0

Views: 93

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276266

You can use a computed observable for that.

function ViewModel(){
   var obj = {Group1: 0, Group2: 1, Group3: 2, Group4: 3, Group5: 4}; // Your object

   this.data = ko.computed(function(){
      // works on modern browsers (keys/map), old ones would need 
      // a shim or for in loop
      return Object.keys(obj).map(function(elem){ 
          return {val:elem+" -> "+obj[elem]};
       });
   });
}

ko.applyBindings(new ViewModel());

Fiddle

Upvotes: 1

Related Questions